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

2017-02-08 01:57:29   php

  php   laravel   jwt  

安装

"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. 'api' => [
  7. 'driver' => 'jwt',
  8. 'provider' => 'users',
  9. ],
  10. ]

添加路由

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

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

App\User.php

添加 getJWTIdentifiergetJWTCustomClaims 实现 AuthenticatableUserContract

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

实现路由所需要的控制器

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