溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

laravel安裝jwt-auth及驗(yàn)證的方法

發(fā)布時(shí)間:2020-12-30 12:47:19 來源:億速云 閱讀:250 作者:小新 欄目:編程語言

小編給大家分享一下laravel安裝jwt-auth及驗(yàn)證的方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

laravel 安裝jwt-auth及驗(yàn)證

1、使用composer安裝jwt,cmd到項(xiàng)目文件夾中;

composer require tymon/jwt-auth 1.0.*(這里版本號(hào)根據(jù)自己的需要寫)

安裝jwt ,參考官方文檔https://jwt-auth.readthedocs.io/en/docs/laravel-installation/

2、如果laravel版本低于5.4

打開根目錄下的config/app.php

在'providers'數(shù)組里加上Tymon\JWTAuth\Providers\LaravelServiceProvider::class,

'providers' => [ ... Tymon\JWTAuth\Providers\LaravelServiceProvider::class,]

3、在 config 下增加一個(gè) jwt.php 的配置文件

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

4、在 .env 文件下生成一個(gè)加密密鑰,如:JWT_SECRET=foobar

php artisan jwt:secret

5、在user模型中寫入下列代碼

<?php
namespace App\Model;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
        // Rest omitted for brevity
    protected $table="user";
    public $timestamps = false;
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
    public function getJWTCustomClaims()
    {
        return [];
    }
}

6、注冊(cè)兩個(gè) Facade

config/app.php

'aliases' => [
        ...
        // 添加以下兩行
        'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth',
        'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory',
],

7、修改 auth.php

config/auth.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'jwt',      // 原來是 token 改成jwt
        'provider' => 'users',
    ],
],

8、注冊(cè)路由

Route::group([
    'prefix' => 'auth'
], function ($router) {
    $router->post('login', 'AuthController@login');
    $router->post('logout', 'AuthController@logout');
});

9、創(chuàng)建token控制器

php artisan make:controller AuthController

代碼如下:

<?php
namespace App\Http\Controllers;
use App\Model\User;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }
    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request(['email', 'password']);
        if (! $token = auth('api')->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
        return $this->respondWithToken($token);
    }
    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(JWTAuth::parseToken()->touser());
    }
    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        JWTAuth::parseToken()->invalidate();
        return response()->json(['message' => 'Successfully logged out']);
    }
    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(JWTAuth::parseToken()->refresh());
    }
    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => JWTAuth::factory()->getTTL() * 60
        ]);
    }
}

注意:attempt  一直返回false,是因?yàn)閜assword被加密了,使用bcrypt或者password_hash加密后就可以了

10、驗(yàn)證token獲取用戶信息

有兩種使用方法:

加到 url 中:?token=你的token

加到 header 中,建議用這種,因?yàn)樵?https 情況下更安全:Authorization:Bearer 你的token

11、首先使用artisan命令生成一個(gè)中間件,我這里命名為RefreshToken.php,創(chuàng)建成功后,需要繼承一下JWT的BaseMiddleware

代碼如下:

<?php
namespace App\Http\Middleware;
use Auth;
use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
// 注意,我們要繼承的是 jwt 的 BaseMiddleware
class RefreshToken extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @ param  \Illuminate\Http\Request $request
     * @ param  \Closure $next
     *
     * @ throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
     *
     * @ return mixed
     */
    public function handle($request, Closure $next)
    {
        // 檢查此次請(qǐng)求中是否帶有 token,如果沒有則拋出異常。
        $this->checkForToken($request);
        // 使用 try 包裹,以捕捉 token 過期所拋出的 TokenExpiredException  異常
        try {
            // 檢測(cè)用戶的登錄狀態(tài),如果正常則通過
            if ($this->auth->parseToken()->authenticate()) {
                return $next($request);
            }
            throw new UnauthorizedHttpException('jwt-auth', '未登錄');
        } catch (TokenExpiredException $exception) {
            // 此處捕獲到了 token 過期所拋出的 TokenExpiredException 異常,我們?cè)谶@里需要做的是刷新該用戶的 token 并將它添加到響應(yīng)頭中
            try {
                // 刷新用戶的 token
                $token = $this->auth->refresh();
                // 使用一次性登錄以保證此次請(qǐng)求的成功
                Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
            } catch (JWTException $exception) {
                // 如果捕獲到此異常,即代表 refresh 也過期了,用戶無法刷新令牌,需要重新登錄。
                throw new UnauthorizedHttpException('jwt-auth', $exception->getMessage());
            }
        }
        // 在響應(yīng)頭中返回新的 token
        return $this->setAuthenticationHeader($next($request), $token);
    }
}

這里主要需要說的就是在token進(jìn)行刷新后,不但需要將token放在返回頭中,最好也將請(qǐng)求頭中的token進(jìn)行置換,因?yàn)樗⑿逻^后,請(qǐng)求頭中的token就已經(jīng)失效了,如果接口內(nèi)的業(yè)務(wù)邏輯使用到了請(qǐng)求頭中的token,那么就會(huì)產(chǎn)生問題。

這里使用

$request->headers->set('Authorization','Bearer '.$token);

將token在請(qǐng)求頭中刷新。

創(chuàng)建并且寫完中間件后,只要將中間件注冊(cè),并且在App\Exceptions\Handler.php內(nèi)加上一些異常處理就ok了。

12、kernel.php文件中

$routeMiddleware 添加中間件配置

'RefreshToken' => \App\Http\Middleware\RefreshToken::class,

13、添加路由

Route::group(['prefix' => 'user'],function($router) {
    $router->get('userInfo','UserController@userInfo')->middleware('RefreshToken');
});

在控制器中通過  JWTAuth::user();就可以獲取用戶信息

以上是“l(fā)aravel安裝jwt-auth及驗(yàn)證的方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI