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' => AppHttpMiddlewareAuthenticate::class,
]);
$app->register(AppProvidersAppServiceProvider::class);
$app->register(AppProvidersAuthServiceProvider::class);

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

$this->app->register(TymonJWTAuthProvidersLumenServiceProvider::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配置并编辑
复制blogvendorlaravellumen-frameworkconfigauth.php到blogconfigauth.php
修改blogconfigauth.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' => AppUser::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' => [
//
],
];

增加登录控制器AuthController.php
纯lumen下AuthController.php示例
新建blogappHttpControllersAuthController.php
代码如下:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use TymonJWTAuthExceptionsJWTException;
use TymonJWTAuthExceptionsTokenExpiredException;
use TymonJWTAuthExceptionsTokenInvalidException;
use TymonJWTAuthJWTAuth;

class AuthController extends Controller
{
protected $jwt;

public function __construct(JWTAuth $jwt)
{
$this->jwt = $jwt;
}

public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email|max:255',
'password' => 'required',
]);

try {
if (! $token = $this->jwt->attempt($request->only('email', 'password'))) {
return response()->json(['user_not_found'], 404);
}
} 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());
}

return response()->json(compact('token'));
}
}


lumen+dingo/api下AuthController.php示例
新建blogappHttpControllersv1AuthController.php
代码如下:

<?php

namespace AppHttpControllersv1;

use AppHttpControllersController;
use IlluminateHttpRequest;
use TymonJWTAuthExceptionsJWTException;
use TymonJWTAuthExceptionsTokenExpiredException;
use TymonJWTAuthExceptionsTokenInvalidException;
use TymonJWTAuthJWTAuth;

class AuthController extends Controller
{
protected $jwt;

public function __construct(JWTAuth $jwt)
{
$this->jwt = $jwt;
}

public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email|max:255',
'password' => 'required',
]);

try {
if (! $token = $this->jwt->attempt($request->only('email', 'password'))) {
return response()->json(['user_not_found'], 404);
}
} 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());
}

return response()->json(compact('token'));
}
}


增加路由
纯lumen下路由示例
<?php
$router->post('auth/login', 'AuthController@login');

lumen+dingo/api下路由示例
<?php
$api = app('DingoApiRoutingRouter');
/** @var DingoApiRoutingRouter $api */
$api->version('v1', ['namespace' => 'AppHttpControllersv1'],function ($api) {
/** @var DingoApiRoutingRouter $api */
$api->post('auth/login', 'AuthController@login');
$api->get('hello_world','HelloWorldController@index');
});

User类(model)代码:

<?php

namespace App;

use IlluminateAuthAuthenticatable;
use IlluminateContractsAuthAccessAuthorizable as AuthorizableContract;
use IlluminateContractsAuthAuthenticatable as AuthenticatableContract;
use IlluminateDatabaseEloquentModel;
use LaravelLumenAuthAuthorizable;
use TymonJWTAuthContractsJWTSubject;

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

原文地址:https://www.cnblogs.com/smilevv/p/13352664.html