官方文档
1.控制器
代码语言:javascript复制use TymonJWTAuthExceptionsTokenExpiredException;
use TymonJWTAuthFacadesJWTAuth;
public function getAuthenticatedUser()
{
try {
if (! $user = JWTAuth::parseToken()->authenticate()) {
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->getStatusCode());
}
$userid = $user->id;//返回用户id
return response()->json(compact('userid'));
}
postMan调用接口传入token
2.直接输入token获取用户信息
代码语言:javascript复制function getAuthenticatedUser()
{
$token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9zb2NpYWwuemloYW56eS5jb21cL2FwaVwvdjFcL2F1dGhvcml6YXRpb25zIiwiaWF0IjoxNTk2MzUyNjk2LCJleHAiOjE1OTYzNTYyOTYsIm5iZiI6MTU5NjM1MjY5NiwianRpIjoidUdVZE1zaVY1amQ4UTZhRyIsInN1YiI6MiwicHJ2IjoiODdlMGFmMWVmOWZkMTU4MTJmZGVjOTcxNTNhMTRlMGIwNDc1NDZhYSJ9.JWWYOYaU5QziuBRTUI2cbk_FBTiexL26kR2JjcoU43M'
try {
if (! $user = JWTAuth::setToken($token)->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (TymonJWTAuthExceptionsTokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (TymonJWTAuthExceptionsTokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (TymonJWTAuthExceptionsJWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
} catch (IlluminateAuthAuthenticationException $e){
}
// the token is valid and we have found the user via the sub claim
return $user->id;
}