测试使用的是Laravel5.5版本。
安装
?
1
|
composer require tymon /jwt-auth =1.0.0-rc.5
|
配置
生成配置
?
1
2
3
|
php artisan vendor:publish --provider= "Tymon\\JWTAuth\\Providers\\LaravelServiceProvider"
php artisan jwt:secret
|
auth配置
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
<?php
return [
...
'defaults' => [
'guard' => 'web' ,
'passwords' => 'users' ,
],
'guards' => [
'web' => [
'driver' => 'session' ,
'provider' => 'users' ,
],
// 使用jwt
'api' => [
'driver' => 'jwt' ,
'provider' => 'apiUser' ,
],
],
'providers' => [
...
// 指定model
'apiUser' => [
'driver' => 'eloquent' ,
'model' => App\\ApiUser:: class ,
],
],
];
|
编码
控制器:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
<?php
namespace App\\Http\\Controllers\\Api;
use App\\ApiUser;
use App\\Http\\Controllers\\Controller;
use Illuminate\\Http\\Request;
use Tymon\\JWTAuth\\Facades\\JWTAuth;
class AuthController extends Controller
{
/**
* 中间件去除login和refresh
*
* @return void
*/
public function __construct()
{
$this ->middleware( 'auth:api' , [ 'except' => [ 'login' , 'refresh' ]]);
}
/**
* Get a JWT via given credentials.
*
* @return \\Illuminate\\Http\\JsonResponse
*/
public function login(Request $request )
{
$credentials = $request ->only( 'phone' , 'password' );
if ( count ( $credentials ) < 2) {
return response()->json([ 'error' => 'Unauthorized' ], 401);
}
$user = ApiUser::where( 'phone' , $credentials [ 'phone' ])
->where( 'password' , md5( $credentials [ 'password' ]))
->first();
if ( empty ( $user ) || ! $token = JWTAuth::fromUser( $user )) {
return response()->json([ 'error' => 'Unauthorized' ], 401);
}
// dd($token);
return $this ->respondWithToken( $token );
}
/**
* Get the authenticated User.
*
* @return \\Illuminate\\Http\\JsonResponse
*/
public function me()
{
return response()->json(auth( 'api' )->user());
}
/**
* Log the user out (Invalidate the token).
*
* @return \\Illuminate\\Http\\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json([ 'message' => 'Successfully logged out' ]);
}
/**
* Refresh a token.
*
* @return \\Illuminate\\Http\\JsonResponse
*/
public function refresh()
{
return $this ->respondWithToken(auth( 'api' )->refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \\Illuminate\\Http\\JsonResponse
*/
protected function respondWithToken( $token )
{
return response()->json([
'access_token' => $token ,
'token_type' => 'bearer' ,
'expires_in' => auth( 'api' )->factory()->getTTL() * 60
]);
}
}
|
路由:
此处注意,我为了方便测试,使用了get方法,生产环境不建议使用get。
?
1
2
3
4
5
6
7
8
|
// routes/api.php
Route::middleware( 'api' )->prefix( 'auth' )-> namespace ( 'Api' )->group( function () {
Route::get( 'login' , 'AuthController@login' );
Route::post( 'logout' , 'AuthController@logout' );
Route::get( 'refresh' , 'AuthController@refresh' );
Route::get( 'me' , 'AuthController@me' );
});
|
测试一下:
unauthenticated处理
这里需要注意下,unauthenticated处理一下比较好,否则会默认跳转login登录页面。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<?php
namespace App\\Exceptions;
use Exception;
use Illuminate\\Foundation\\Exceptions\\Handler as ExceptionHandler;
use Illuminate\\Auth\\AuthenticationException;
class Handler extends ExceptionHandler
{
...
protected function unauthenticated( $request , AuthenticationException $exception )
{
return response()->json([ 'message' => 'Unauthenticated.' ], 401);
/*非api可以这么处理
return $request->expectsJson()
? response()->json(['message' => 'Unauthenticated.'], 401)
: redirect()->guest(route('login'));
*/
}
}
|
加入token refresh
加入中间件代码:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<?php
namespace App\\Http\\Middleware;
use Closure;
use Tymon\\JWTAuth\\Facades\\JWTAuth;
use Tymon\\JWTAuth\\Exceptions\\JWTException;
use Illuminate\\Auth\\AuthenticationException;
use Tymon\\JWTAuth\\Exceptions\\TokenExpiredException;
use Illuminate\\Http\\Exceptions\\HttpResponseException;
use Tymon\\JWTAuth\\Http\\Middleware\\BaseMiddleware;
class RefreshToken extends BaseMiddleware
{
/**
* Handle an incoming request.
*
* @param \\Illuminate\\Http\\Request $request
* @param \\Closure $next
* @return mixed
*/
public function handle( $request , Closure $next )
{
try {
//检查请求中是否带有token 如果没有token值则抛出异常
$this ->checkForToken( $request );
if ( $request ->user = JWTAuth::parseToken()->authenticate()) {
return $next ( $request );
}
throw new AuthenticationException( 'Unauthorized' , []);
} catch (TokenExpiredException $exception ){
//返回特殊的code
throw new HttpResponseException(response()->json([
'message' => 'token expired'
]));
} catch (\\Exception $exception ) {
throw new AuthenticationException( 'Unauthorized' , []);
}
}
}
|
注册:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<?php
namespace App\\Http;
use Illuminate\\Foundation\\Http\\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
...
protected $routeMiddleware = [
'token.refresh' => \\App\\Http\\Middleware\\RefreshToken:: class ,
'auth.basic' => \\Illuminate\\Auth\\Middleware\\AuthenticateWithBasicAuth:: class ,
'bindings' => \\Illuminate\\Routing\\Middleware\\SubstituteBindings:: class ,
'can' => \\Illuminate\\Auth\\Middleware\\Authorize:: class ,
'guest' => \\App\\Http\\Middleware\\RedirectIfAuthenticated:: class ,
'throttle' => \\Illuminate\\Routing\\Middleware\\ThrottleRequests:: class ,
];
}
|
相应的控制器构造函数修改:
?
1
2
3
4
|
public function __construct()
{
$this ->middleware( 'token.refresh' , [ 'except' => [ 'login' , 'refresh' ]]);
}
|
把token时间设置成1分钟,测试一下。
可以根据api返回,去调用刷新接口。
简单使用就是这样啦。
总结
到此这篇关于Laravel配合jwt使用的文章就介绍到这了,更多相关Laravel配合jwt使用内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!
原文链接:https://segmentfault.com/a/1190000037524366
相关文章
猜你喜欢
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-27 75
-
Java concurrency集合之ConcurrentSkipListSet_动力节点Java学院整理
2025-05-29 21 -
2025-05-29 21
-
外贸建站系统推荐:CMS平台选择与WordPress教程指南
2025-05-25 25 -
Win11下载速度被限制怎么办 Win11下载速度被限制解决方法
2025-05-27 25
热门评论