jwt laravel 常用方法

2019-03-06 10:53:34   php分享记录

  jwt方法  

jwt laravel 常用方法

  1. 方法
  2. Auth防护实例提供以下方法。
  3. 多个卫兵
  4. 如果新创建的“api”防护未设置为默认防护,或者您已定义多个防护来处理身份验证,则应在调用auth()时指定防护。
  5. $token = auth('api')->attempt($credentials);
  6. 尝试()
  7. 尝试通过某些凭据对用户进行身份验证。
  8. // Generate a token for the user if the credentials are valid
  9. $token = auth()->attempt($credentials);
  10. 这将返回jwt null
  11. 登录()
  12. 记录用户并为其返回一个jwt
  13. // Get some user from somewhere
  14. $user = User::first();
  15. // Get the token
  16. $token = auth()->login($user);
  17. 用户()
  18. 获取当前经过身份验证的用户。
  19. // Get the currently authenticated user
  20. $user = auth()->user();
  21. 如果用户未经过身份验证,null则会返回。
  22. userOrFail()
  23. 获取当前经过身份验证的用户或抛出异常。
  24. try {
  25. $user = auth()->userOrFail();
  26. } catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {
  27. // do something
  28. }
  29. 如果未设置用户,则将Tymon\JWTAuth\Exceptions\UserNotDefinedException抛出a
  30. 登出()
  31. 将用户注销 - 这将使当前令牌无效并取消设置经过身份验证的用户。
  32. auth()->logout();
  33. // Pass true to force the token to be blacklisted "forever"
  34. auth()->logout(true);
  35. 刷新()
  36. 刷新令牌,使当前令牌无效
  37. $newToken = auth()->refresh();
  38. // Pass true as the first param to force the token to be blacklisted "forever".
  39. // The second parameter will reset the claims for the new token
  40. $newToken = auth()->refresh(true, true);
  41. 无效()
  42. 使令牌无效(将其添加到黑名单)
  43. auth()->invalidate();
  44. // Pass true as the first param to force the token to be blacklisted "forever".
  45. auth()->invalidate(true);
  46. tokenById()
  47. 根据给定用户的ID获取令牌。
  48. $token = auth()->tokenById(123);
  49. 有效载荷()
  50. 获取原始JWT有效负载
  51. $payload = auth()->payload();
  52. // then you can access the claims directly e.g.
  53. $payload->get('sub'); // = 123
  54. $payload['jti']; // = 'asfe4fq434asdf'
  55. $payload('exp') // = 123456
  56. $payload->toArray(); // = ['sub' => 123, 'exp' => 123456, 'jti' => 'asfe4fq434asdf'] etc
  57. 验证()
  58. 验证用户的凭据
  59. if (auth()->validate($credentials)) {
  60. // credentials are valid
  61. }
  62. 更高级的用法
  63. 添加自定义声明
  64. $token = auth()->claims(['foo' => 'bar'])->attempt($credentials);
  65. 明确设置标记
  66. $user = auth()->setToken('eyJhb...')->user();
  67. 显式设置请求实例
  68. $user = auth()->setRequest($request)->user();
  69. 覆盖令牌ttl
  70. $token = auth()->setTTL(7200)->attempt($credentials);