laravel JWT/jwt安裝使用

https://learnku.com/articles/10885/full-use-of-jwt

安裝

composer.json的require中加入下面的包,composer install

"tymon/jwt-auth": "1.0.0-rc4.1"
在 config/app.php 中provider中添加

Tymon\JWTAuth\Providers\LaravelServiceProvider::class,  
在 config/app.php 中aliases中添加

'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
發佈配置文件
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"


生成密鑰
php artisan jwt:secret

使用

先引入下面內容:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
config/auth.php
api->driver=>'token',修改爲'jwt'
'api' => [
    'driver' => 'jwt',
    'provider' => 'users',
],

在exceptopns中的Handler 的render方法中加入下面代碼全局定義返回錯誤

switch ($exception) {
            case ($exception instanceof AuthenticationException):
                return Response::error(401, $exception->getMessage());
            case ($exception instanceof ValidationException):
                return Response::error(422, 'params error', ($exception->errors()));
            default:
                return Response::error(500, '未知錯誤');
        }
        return parent::render($request, $exception);

將用戶模型關聯上

 

1. 通過token獲取用戶

JWTAuth::toUser( $tokenStr );

 

2. 通過用戶獲取token

在需要的模型裏面添加

在需要的模型裏面添加
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends  Authenticatable implements JWTSubject
public function getJWTIdentifier()
{
    return $this->getKey();
}

/**
 * Return a key value array, containing any custom claims to be added to the JWT.
 *
 * @return array
 */
public function getJWTCustomClaims()
{
    return [];
}

//在需要的地方使用下面的方法生成token
$user = JWTAuth::fromUser( $model );

 

 

 

3. 使用負載(payload) 生成token

一般是不能用於登陸的(如果登陸的用戶生成的token,則可以用於登陸)

 

// 創建負載
$customClaims = ['foo' => 'bar', 'baz' => 'bob'];

$payload = JWTFactory::make($customClaims);

$token = JWTAuth::encode($payload);

 

登錄

public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }

    /**
     * Get a JWT token via given credentials.
     *
     * @param  \Illuminate\Http\Request  $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        //$token = JWTAuth::fromUser( $UserModel );這種也可以
        if ($token = $this->guard()->attempt($credentials)) {
            return $this->respondWithToken($token);
        }
        return response()->json(['error' => 'Unauthorized'], 401);
    }

4.退出

 $this->guard()->logout();
 或
 JWTAuth::parseToken()->invalidate();

 

5.刷新token

 public function refresh()
    {
        return $this->respondWithToken($this->guard()->refresh());
    }

 

6.返回token

protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            //過期時間
            'expires_in' => $this->guard()->factory()->getTTL() * 60
        ]); 
    }

 

返回用戶信息

public function me()
    {
         return response()->json($this->guard()->user());
         或
        return response()->json(JWTAuth::parseToken()->touser());
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章