在Lumen中使用jwt生成token和鉴权
参考:https://blog.csdn.net/weixin_43303732/article/details/90443408
步骤:
- 添加依赖包:tymon/jwt-auth
- 生成密钥
- 启用jwt
- 修改Model
- 编写接口,生成token
- 配置鉴权
- 编写接口,测试用auth中间件鉴权
1) 添加依赖:
composer require tymon/jwt-auth
2)生成密钥
.env 文件下生成一个加密密钥
php artisan jwt:secret
3) 启用jwt
修改文件:bootstrap\app.php
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);
4)修改模型(Model)
<?php
namespace App\Models;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
use Authenticatable, Authorizable, HasFactory;
....略
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [
'data'=>$this->data
];
}
}
5)编写接口,生成token
新建文件:app\Http\Controllers\AuthController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class AuthController
{
public function postLogin(Request $request)
{
$username = $request->json('username');
$password = $request->json('password');
$user = User::where('name', $username)->where('password', $password)->first();
$user->data = [
'nickname'=>'测试',
'username'=>$username,
'url'=>'url'
];
if ($user) {
$token = Auth::login($user);
return [
'status'=>200,
'data'=>[
'token'=>$token
]
];
}else{
return [
'status'=>500,
'message'=>'帐号不存在'
];
}
}
}
添加路由:routes\web.php
$router->post('/api/auth/login', '\App\Http\Controllers\AuthController@postLogin');
测试:
POST http://xxxx/api/auth/login
Content-Type:application/json
{
"username":"test",
"password":"123456"
}
返回:(https://tool.box3.cn/jwt.html 可以查看token解析出的结果,payload中的[sub]即数据库用户的id)
{
"status": 200,
"data":{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC92Y2hhdGJvdC5sb2NcL2FwaVwvYXV0aFwvbG9naW4iLCJpYXQiOjE2MzEwODYyMTcsImV4cCI6MTYzMTA4OTgxNywibmJmIjoxNjMxMDg2MjE3LCJqdGkiOiJ4RXdEeThGcE5KM09NdUdoIiwic3ViIjoxLCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3IiwiZGF0YSI6eyJuaWNrbmFtZSI6Ilx1NmQ0Ylx1OGJkNSIsInVzZXJuYW1lIjoidGVzdCIsInVybCI6InVybCJ9fQ.GmFd5AgT2FOzkW3O_c10dUPdRLj7FDLiu_HHZxqR0f4"
}
}
6)配置鉴权
检查文件是否存在:config\auth.php
如果不存在可以把:vendor\laravel\lumen-framework\config\auth.php复制过来。
修改文件:config\auth.php
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users'
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\Models\User::class,
],
],
修改文件:bootstrap\app.php
$app->configure('auth'); // 添加代码
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class, // 打开注释
]);
$app->register(App\Providers\AuthServiceProvider::class); // 打开注释
7)编写接口,测试用auth中间件鉴权
控制器中添加方法:app\Http\Controllers\AuthController.php
public function test(Request $request)
{
var_dump(Auth::user()->id);
}
配置路由:
$router->group([
'prefix'=>'api/jwt',
'middleware'=>'auth'
], function() use ($router){
$router->get('test', '\App\Http\Controllers\AuthController@test');
});
测试:
GET http://xxxx/api/jwt/test
Authorization:Bearer 这里填token(Bearer+空格+token)
返回:
int(1)
如token无效返回:
Unauthorized.
注:
jwt的配置参数可以查看:vendor\tymon\jwt-auth\config\config.php
可以使用vendor\tymon\jwt-auth\src\Http\Middleware\Authenticate.php代替默认的鉴权中间件。
|