jwt-auth

未匹配的标注

搭建 JWT

安装

composer require tymon/jwt-auth dev-develop

发布配置文件

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

生成密钥

php artisan jwt:secret

配置 Auth guard

修改 config/auth.php

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

User Model 更改

修改 app/Models/User.php

<?php
...
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    ...
    /**
     * 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 [];
    }
}

implements JWTSubject 记得加

JWT 认证逻辑

php artisan make:controller AuthController

无痛刷新 token

创建自定义中间件 RefreshToken

php artisan make:middleware RefreshToken

内容是:GitHub 上的 app/Http/Middleware/RefreshToken.php

注册自定义中间件。修改 app/Http/Kernel.php,添加:

    ...
    protected $routeMiddleware = [
        ...
        'refresh' => \App\Http\Middleware\RefreshToken::class,
    ];
    ...

参考

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 查看所有版本


暂无话题~