0%

Laravel JWT auth 捕获异常

lravel 5.8 使用jwt-auth,捕获异常

1
2
3
$this->middleware('jwt.auth', ['except' => ['login']]);
// 另外关于上面的中间件,官方文档写的是『auth:api』
// 但是我推荐用 『jwt.auth』,效果是一样的,但是有更加丰富的报错信息返回

会报错401,打印sql 发现是config\auth.php guards 需要设置为默认值为api,如果没有就会读取默认的tables查询user。着急,两种方法记录一下,日后在完善。
修改:

1
2
3
4
5
6
7
8
9
$this->middleware('auth:api', ['except' => ['login']]);
// 指定guards 为 api
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'admin_users',
'hash' => false,
],
]

修改\app\Http\Middleware\Authenticate.php,重写authenticate($request, array $guards)

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
/**
* @param \Illuminate\Http\Request $request
* @param array $guards
* @return \Illuminate\Http\JsonResponse|void
* @throws AuthenticationException
*/
protected function authenticate($request, array $guards)
{
if (empty($guards)) {
$guards = [null];
}

foreach ($guards as $guard) {
if ($this->auth->guard($guard)->check()) {
return $this->auth->shouldUse($guard);
}
}
if($guards[0]=='api'){
try
{
if (! $user = \JWTAuth::parseToken()->authenticate())
{
return response()->json([
'error' => true,
'code' => 10,
'data' => [
'message' => 'User not found by given token'
]
]);
}

} catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json([
'error' => true,
'code' => 11,
'data' => [
'message' => 'Token Expired'
]
]);

} catch (TokenInvalidException $e) {
return response()->json([
'error' => true,
'code' => 12,
'data' => [
'message' => 'Invalid Token'
]
]);

} catch (JWTException $e) {
return response()->json([
'error' => true,
'code' => 13,
'data' => [
'message' => 'Token absent'
]
]);
}
}
throw new AuthenticationException(
'Unauthenticated.', $guards, $this->redirectTo($request)
);
}

也可以写在这里
\app\Exceptions\Handler.php

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
<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];

/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];

/**
* Report or log an exception.
* @param Exception $exception
* @return mixed|void
* @throws Exception
*/
public function report(Exception $exception)
{
parent::report($exception);
}

/**
* Render an exception into an HTTP response.
* @param \Illuminate\Http\Request $request
* @param Exception $exception
* @return \Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
*/
public function render($request, Exception $exception)
{
//也可以在这里写
// if ($exception instanceof AuthenticationException){
// $guard = $exception->guards()[0];
// if ($guard=='api'){
// $preException = $exception->getPrevious();
// return response()->json(['error' => 'TOKEN_INVALID']);
// }
// }
if ($exception instanceof UnauthorizedHttpException) {
$preException = $exception->getPrevious();
if ($preException instanceof
\Tymon\JWTAuth\Exceptions\TokenExpiredException) {
return response()->json(['error' => 'TOKEN_EXPIRED']);
} else if ($preException instanceof
\Tymon\JWTAuth\Exceptions\TokenInvalidException) {
return response()->json(['error' => 'TOKEN_INVALID']);
} else if ($preException instanceof
\Tymon\JWTAuth\Exceptions\TokenBlacklistedException) {
return response()->json(['error' => 'TOKEN_BLACKLISTED']);
}
if ($exception->getMessage() === 'Token not provided') {
return response()->json(['error' => 'Token not provided']);
}
}
return parent::render($request, $exception);
}
}