Laravel 版本:

Laravel Framework 6.18.3

查看版本命令:

php artisan -V

1、安装JWT扩展包:

composer require tymon/jwt-auth:dev-develop --prefer-source

2、发布配置文件:

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

3、生成JWT密钥:

php artisan jwt:secret

4、在 app/Http/Kernel.php 中注册 auth.jwt 中间件:

protected $routeMiddleware = [
....
'auth.jwt' => \Tymon\JWTAuth\Http\Middleware\Authenticate::class,
];

5、设置路由:

Route::post('login', 'ApiController@login');
Route::post('register', 'ApiController@register');
Route::group(['middleware' => 'auth.jwt'], function () {
Route::get('logout', 'ApiController@logout');
  Route::get('user', 'ApiController@getAuthUser');
});

6、更新User模型:

JWT 需要在 User 模型中实现 Tymon\JWTAuth\Contracts\JWTSubject 接口。 此接口需要实现两个方法  getJWTIdentifier 和 getJWTCustomClaims。使用以下内容更新 app/User.php 。

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject; class User extends Authenticatable implements JWTSubject
{
use Notifiable; /**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
]; /**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
]; /**
* 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 [];
}
}

7、修改config/auth.php文件:

'guards' => [     
   ....
'admin' => [
'driver' => 'jwt',
'provider' => 'admins',
],
]
'providers' => [
     ....
'admins' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
]

8、控制器示例:

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Tymon\JWTAuth\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException; class ApiController extends Controller
{
public $loginAfterSignUp = true; public function register(Request $request)
{
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save(); if ($this->loginAfterSignUp) {
return $this->login($request);
} return response()->json([
'success' => true,
'data' => $user
], 200);
} public function login(Request $request)
{
$input = $request->only('email', 'password');
$jwt_token = null;
$guard = auth('admin');
if (!$jwt_token = $guard->attempt($input)) {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
} return response()->json([
'success' => true,
'token' => $jwt_token,
]);
} public function logout(Request $request)
{
$this->validate($request, [
'token' => 'required'
]); try {
$guard = auth('admin');
$guard->invalidate($request->token); return response()->json([
'success' => true,
'message' => 'User logged out successfully'
]);
} catch (JWTException $exception) {
return response()->json([
'success' => false,
'message' => 'Sorry, the user cannot be logged out'
], 500);
}
} public function getAuthUser(Request $request)
{
$this->validate($request, [
'token' => 'required'
]); $user = JWTAuth::authenticate($request->token); return response()->json(['user' => $user]);
}
}

注意:如果你的模型不是user,务必修改 /config/auth.php 此参数:

'defaults' => [
'guard' => 'admin',//修改为使用的guard
'passwords' => 'users',
],

Enjoy it !

....

最新文章

  1. psutil一个基于python的跨平台系统信息跟踪模块
  2. HelloWorld的Sprint计划会议
  3. linux增加根分区大小
  4. Hello又大了一岁
  5. perl post 带上请求头
  6. hive集成sentry
  7. 实现Runnable接口和继承Thread类之间的区别
  8. 微信小程序调接口常见问题解决方法
  9. RHEL 6 mdadm 实现Soft Raid
  10. Flask--Web From 表单
  11. cp备份操作时如何忽略指定的目录
  12. ReactNative学习笔记(四)热更新和增量更新
  13. C++解析 xml,用到pugixml库
  14. Jmeter 接口测试知识梳理——环境搭建篇
  15. 使用Swagger2构建强大的RESTful API文档(1)(二十二)
  16. Nodejs的模块系统
  17. C# Language Specification 5.0 (翻译)第一章 引言
  18. pandas练习(一)------ 了解数据
  19. Mybatis处理列名—字段名映射— 驼峰式命名映射
  20. Atitit.Gui按钮与面板---项目规模的评估----文件数统计,结构,代码行数,每类型文件行数.

热门文章

  1. laravel中间件的创建思路分析
  2. Java 添加、删除Excel表单控件
  3. Mybatis在xml配置文件中处理SQL中的大于小于号的方法
  4. 【笔记3-31】Python语言基础-序列sequence
  5. ClickHouse学习系列之二【用户权限管理】
  6. Prism 源码解读7-导航
  7. Python中的编码及操作文件
  8. 【STM32项目笔记】STM32CubeMX+Keil+Proteus联合实现LED闪烁
  9. 九九乘法表 C语言
  10. flask 入门 之 Python Shell (一)