欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Laravel 使用 JWT (Json Web Token) 做 API 认证之tymon/jwt-auth 1.0.0-beta.1实践

安装

"tymon/jwt-auth": "1.0.0-beta.1" 添加到 composer.json 中,执行 composer update

Providers

config/app.php 中在 providers 里添加 Tymon\JWTAuth\Providers\LaravelServiceProvider::class,

Class Aliases

config/app.php 中在 aliases 里添加 'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class

修改认证驱动

修改config/auth.php,将 api 的 driver 修改为 jwt。如下:


  1. 'guards' => [
  2. 'web' => [
  3. 'driver' => 'session',
  4. 'provider' => 'users',
  5. ],
  6.  
  7. 'api' => [
  8. 'driver' => 'jwt',
  9. 'provider' => 'users',
  10. ],
  11. ]

添加路由

在 routes/api.php 中添加以下路由:


  1. $api = app('Dingo\Api\Routing\Router');
  2.  
  3. $api->version('v1', ['namespace' => 'App\Http\Controllers\Api\V1'], function($api) {
  4. $api->post('token', 'UserController@token'); //获取token
  5. $api->post('refresh-token', 'UserController@refershToken'); //刷新token
  6.  
  7. $api->group(['middleware' => ['auth:api']], function($api) {
  8. $api->post('logout', 'UserController@logout'); //登出
  9. $api->get('me', 'UserController@me'); //关于我
  10. });
  11.  
  12. });

App\User.php

添加 getJWTIdentifier 和 getJWTCustomClaims 实现 AuthenticatableUserContract


  1. <?php
  2.  
  3. namespace App\Models;
  4.  
  5. use Illuminate\Notifications\Notifiable;
  6. use Illuminate\Foundation\Auth\User as Authenticatable;
  7. use Tymon\JWTAuth\Contracts\JWTSubject as AuthenticatableUserContract;
  8.  
  9. class User extends Authenticatable implements AuthenticatableUserContract
  10. {
  11.  
  12.  
  13. /**
  14. * The attributes that should be hidden for arrays.
  15. *
  16. * @var array
  17. */
  18. protected $hidden = [
  19. 'password', 'remember_token',
  20. ];
  21.  
  22. /**
  23. * @return mixed
  24. */
  25. public function getJWTIdentifier()
  26. {
  27. return $this->getKey(); // Eloquent model method
  28. }
  29.  
  30. /**
  31. * @return array
  32. */
  33. public function getJWTCustomClaims()
  34. {
  35. return [];
  36. }
  37.  
  38. }

实现路由所需要的控制器


  1. <?php
  2.  
  3. namespace App\Http\Controllers\Api\V1;
  4.  
  5. use App\Http\Controllers\Api\V1\Controller;
  6. use App\Models\User;
  7. use Illuminate\Http\Request;
  8. use Tymon\JWTAuth\Exceptions\JWTException;
  9. use Auth;
  10.  
  11. class UserController extends Controller
  12. {
  13.  
  14. protected $guard = 'api';
  15.  
  16. /**
  17. * 获取token
  18. *
  19. * @param Request $request
  20. * @return \Illuminate\Http\JsonResponse
  21. */
  22. public function token(Request $request)
  23. {
  24. $credentials=[
  25. 'email' => $request->email,
  26. 'password' => $request->password,
  27. 'status' => 0,
  28. ];
  29.  
  30. try {
  31. if (! $token = Auth::guard($this->guard)->attempt($credentials)) {
  32. return response()->json(['error' => 'invalid_credentials'], 401);
  33. }
  34. } catch (JWTException $e) {
  35. return response()->json(['error' => 'could_not_create_token'], 500);
  36. }
  37.  
  38. return response()->json(compact('token'));
  39. }
  40.  
  41. /**
  42. * @return mixed
  43. */
  44. public function refershToken()
  45. {
  46. $token = Auth::guard($this->guard)->refresh();
  47.  
  48. return $this->response->array(compact('token'));
  49. }
  50.  
  51. /**
  52. * 个人信息
  53. *
  54. * @return User|null
  55. */
  56. public function me()
  57. {
  58. return Auth::guard('api')->user();
  59. }
  60.  
  61. /**
  62. * 退出
  63. *
  64. * @return \Illuminate\Http\JsonResponse
  65. */
  66. public function logout()
  67. {
  68. Auth::guard($this->guard)->logout();
  69. return response()->json(['status' => 'ok']);
  70. }
  71. }
来自 https://www.moell.cn/article/37
普通分类: