Laravel 5.7 和 JSON Web 令牌(tymon/jwt-auth) - 用户认证

安装 jwt-auth

增加到 composer.json:

"require": {
    ...

    "tymon/jwt-auth": "1.0.0-rc.3"
}

执行更新 Composer 命令:

composer update

基本配置

生成密钥:

php artisan jwt:secret

发布配置文件:

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

增加到中间件

开启 app/Http/Kernel.php 并在 $routeMiddleware 增加以下中间件:

'jwt.auth' => \Tymon\JWTAuth\Http\Middleware\Authenticate::class,
'jwt.refresh' => \Tymon\JWTAuth\Http\Middleware\RefreshToken::class,

更新用户模型

开启 User.php 并为模型实现 JWTSubject

use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject

并在模型中添加2个方法:

更多:Jwt-auth 官方指南 - 更新用户模型

/**
  * Get the identifier that will be stored in the subject claim of the JWT.
  *
  * @return mixed
  */
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 [];
}

设定 auth.php

开启 config/auth.php 并将 apidriver 更改为 jwt (默认为 token):

'guards' => [
    ...
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

登录方法

在您的用户认证控制器 (當前示例為 APILoginController) 中添加此方法:

public function login() {
    $credentials = request(['email', 'password']);

    if (!$token = auth('api')->attempt($credentials)) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }

    return response()->json([
        'token' => $token,
        'expires' => auth('api')->factory()->getTTL() * 60,
    ]);
}

增加路由

开启 routes/api.php 增加登入路由:

Route::post('login', 'APILoginController@login');

增加中间件 jwt.auth 以保护路由:

Route::middleware('jwt.auth')->get('users', function () {
    return auth('api')->user();
});

然后将 Authorization: Bearer {token} 添加到标头请求中。

捕获异常

如果你想捕获异常,可在 app/Exceptions/Handler.php 中,render 方法中捕获错误:

use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

...

if ($exception instanceof UnauthorizedHttpException) {
    $preException = $exception->getPrevious();

    if ($preException instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException) {
        return response()->json(['error' => 'TOKEN_EXPIRED']);
    } else if ($preException instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException) {
        return response()->json(['error' => 'TOKEN_INVALID']);
    } else if ($preException instanceof \Tymon\JWTAuth\Exceptions\TokenBlacklistedException) {
        return response()->json(['error' => 'TOKEN_BLACKLISTED']);
   }

    if ($exception->getMessage() === 'Token not provided') {
        return response()->json(['error' => 'Token not provided']);
    }
}

以上。

原文出自:Laravel 5.7 and JSON Web Tokens (tymon/jwt-auth) — authentication
更多:Jwt-auth 官方指南

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 2

发布配置文件指令写错了
是 --provider

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!