lumen7+jwt相对正确的使用方式

U.R.M.L 2020-06-12 19:07:18 78 收藏
分类专栏: Lumen JWT Php
————————————————
版权声明:本文为CSDN博主「U.R.M.L」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/urmljyc/java/article/details/106717260

安装JWT
composer require tymon/jwt-auth

修改app.php及AppServiceProvider.php
编辑blog/bootstrap/app.php
取消以下代码注释:
.

$app->withFacades();
$app->withEloquent();

$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);

编辑blog/app/Providers/AppServiceProvider.php
在register方法内添加:

$this->app->register(\Tymon\JWTAuth\Providers\LumenServiceProvider::class);
1
如下图:

 

 


配置env
添加配置项
编辑blog/.env
添加如下配置:

#JWT身份验证密钥,添加完配置后,执行以下命令php artisan jwt:secret将会自动获取JWT身份验证密钥并会自动填充
JWT_SECRET=
#JWT公钥,也可以是JWT公钥文件所在路径
JWT_PUBLIC_KEY=
#JWT私钥,也可以是JWT私钥文件所在路径
JWT_PRIVATE_KEY=
#JWT密码短语,也就是密码,如果不设置,留空即可
JWT_PASSPHRASE=
#JWT令牌有效时长(分钟),默认60分钟,留空则代表令牌永不过期,如果留空则必须从required_claims中移除exp
JWT_TTL=60
#指定JWT令牌刷新的有效时长(分钟),默认2周,留空则代表令牌获得无限刷新时间
JWT_REFRESH_TTL=20160
#JWT签名令牌的哈希算法
JWT_ALGO=HS256
#指定JWT令牌验证期间允许的时间偏差秒数,适用于(`iat`、`nbf`、`exp`)这三种断言,默认是0
JWT_LEEWAY=0
#启用黑名单,要使令牌失效,必须启用黑名单。如果不希望或不需要此功能,请将其设置为false。
JWT_BLACKLIST_ENABLED=true
#黑名单宽限期,当用同一个JWT发出多个并发请求时,由于每一个请求都会再生令牌,其中一些可能会失败,以秒为单位设置宽限期以防止并行请求失败。
JWT_BLACKLIST_GRACE_PERIOD=0


如下图:

 

 


生成JWT_SECRET
执行以下命令,将会自动获取JWT身份验证密钥并会自动填充到.env对应配置中

php artisan jwt:secret
1
增加auth.php配置并编辑
复制blog\vendor\laravel\lumen-framework\config\auth.php到blog\config\auth.php
修改blog\config\auth.php

<?php

return [

/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/

'defaults' => [
'guard' => env('AUTH_GUARD', 'api'),
],

/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "token"
|
*/

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

/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/

'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\User::class,(这个model需要继承JWTSubject)后面有代码:
],
],

/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| Here you may set the options for resetting passwords including the view
| that is your password reset e-mail. You may also set the name of the
| table that maintains all of the reset tokens for your application.
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/

'passwords' => [
//
],
];


测试类:

use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\JWTAuth;

class Controller extends BaseController
{
    protected $jwt;

    public function __construct(JWTAuth $jwt)
    {
        $this->jwt = $jwt;
    }
 // 获取token
    public function token($array)
    {
        try {
            if (!$token = $this->jwt->attempt($array)) {
                return false;//账户与密码不一致
            } else {
                return $token;//返回token值
            }
        } catch (TokenExpiredException $e) {
            return response()->json(['token_expired'], $e->getStatusCode());
        } catch (TokenInvalidException $e) {
            return response()->json(['token_invalid'], $e->getStatusCode());
        } catch (JWTException $e) {
            return response()->json(['token_absent' => $e->getMessage()], $e->getStatusCode());
        }
    }
 // 用户登录
    function signin(Request $request)
    {
                $mobile = $request->input('mobile');//账号
                $password = $request->input('password');//密码
                $state = $request->input('state');//协议状态

                if ($state != 1) {
                    return $this->fail('未同意用户协议');
                }
                if (empty($mobile) || empty($password)) {
                    return $this->fail('填写信息不能为空');

                }
                $token = $this->token(['login_name' => $mobile, 'password' => $password]);//token值(这个是和User模型对应的)
                if ($token == false) {
                    return $this->fail('账户与密码不一致');
                }
                $data['token'] = $token;
                return $this->success($data);
}
}

 

User类(model)代码:

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
    use Authenticatable, Authorizable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password',
    ];

    /**
     * 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 [];
    }
}


测试

 

 

————————————————
版权声明:本文为CSDN博主「U.R.M.L」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/urmljyc/java/article/details/106717260

posted @ 2020-07-21 00:33  Smile☆  阅读(1571)  评论(0编辑  收藏  举报