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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM