lumen5.6配合jwt开发api

lumen5.6配合jwt开发api

2018年08月01日 16:26:17 daily886 阅读数 817

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/daily886/article/details/81333089

目录

通过Composer Create-Project安装lumen

配置lumen

安装 jwt

配置 table

运行 php artisan migrate 生成数据库

配置 路由

配置 guard

配置 app.php

配置 助手函数

配置 用户模型

配置handle 错误处理

配置中间件

配置控制器

最后配置 composer.json

运行 composer dumpauto 命令, 更新自动运行文件

目录结构如下:

生成密钥

用postman请求接口测试

注册请求:

登录请求:

个人信息请求 post => me:

个人信息请求 get => profile:

版本科普

α(Alpha)版

β(Beta)版

RC/ Preview版

普通发行版本

LTS(Long Term Support) 版


通过Composer Create-Project安装lumen

你还可以在终端中通过Composer的create-project命令来安装Lumen

composer create-project --prefer-dist laravel/lumen lumen5.6

配置lumen

Lumen框架的所有配置都存放在.env文件,安装好Lumen后,配置 .env内容:

 
  1. APP_ENV=local #开发: local ,测试: testing ,预上线: staging ,正式环境: production

  2. APP_DEBUG=true #开启debug模式

  3. APP_KEY=base64:yl2XKMVlbjke4e/y1kWanFG9ecaCrteWFBTg4QV4je8= #随机字符串

  4. APP_TIMEZONE=PRC #时区

  5. APP_LOCALE=en #语言英文

  6.  
  7. LOG_CHANNEL=daily #日志记录-按天记录 , vendor /laravel/lumen-framework/config/logging.php 可以配置记录多少天内的日志

  8. LOG_SLACK_WEBHOOK_URL= #暂未使用

  9.  
  10. DB_CONNECTION=mysql #数据库类型

  11. DB_HOST=127.0.0.1 #数据库地址

  12. DB_PORT=3306 #数据库端口

  13. DB_DATABASE=laravel #数据库名称

  14. DB_USERNAME=root #用户名

  15. DB_PASSWORD=root #密码

  16. DB_PREFIX=lumen_ #表前缀

  17.  
  18. CACHE_DRIVER=file #缓存类型

  19. QUEUE_DRIVER=sync #队列驱动 sync 是同步

  20.  
  21. JWT_SECRET=KpH6rJFuMxAGZDyXbDhMPmHdOeT7JhFB #jwt_secret

  22. JWT_TTL=60 #jwt token的有效期

  23. JWT_REFRESH_TTL=1440 #jwt 可以刷新 token 的有效期 , 有效期过后要重新请求token

 

安装 jwt

jwt-auth 最新版本是 1.0.0 rc.2 版本,已经支持了 Laravel 5.6。如果你是 Laravel 5.6 以下版本,也推荐使用最新版本,RC.1 前的版本都存在多用户token认证的安全问题。

 
  1. cd lumen5.6 //切换到项目目录中

  2. // tymon包 https://packagist.org/packages/tymon/jwt-auth

  3. composer require tymon/jwt-auth 1.0.0-rc.2

安装doctrine/dbal扩展

在Laravel和lumen中,使用migration作为数据库的版本控制工具,当需要对已存在的数据表作更改,需要额外引入doctrine/dbal扩展。

composer require doctrine/dbal

配置 table

新建 lumen5.6/database/migrations/2014_10_12_000000_create_users_table.php

 
  1. <?php

  2.  
  3. use Illuminate\Support\Facades\Schema;

  4. use Illuminate\Database\Schema\Blueprint;

  5. use Illuminate\Database\Migrations\Migration;

  6.  
  7. class CreateUsersTable extends Migration

  8. {

  9. /**

  10. * Run the migrations.

  11. *

  12. * @return void

  13. */

  14. public function up()

  15. {

  16. Schema::create('users', function (Blueprint $table) {

  17. $table->increments('id');

  18. $table->string('name');

  19. $table->string('email','50')->unique();

  20. $table->string('password');

  21. $table->string('api_token','500');

  22. $table->rememberToken();

  23. $table->timestamps();

  24. });

  25. }

  26.  
  27. /**

  28. * Reverse the migrations.

  29. *

  30. * @return void

  31. */

  32. public function down()

  33. {

  34. Schema::dropIfExists('users');

  35. }

  36. }

新建 lumen5.6/database/migrations/2014_10_12_100000_create_password_resets_table.php

 
  1. <?php

  2.  
  3. use Illuminate\Support\Facades\Schema;

  4. use Illuminate\Database\Schema\Blueprint;

  5. use Illuminate\Database\Migrations\Migration;

  6.  
  7. class CreatePasswordResetsTable extends Migration

  8. {

  9. /**

  10. * Run the migrations.

  11. *

  12. * @return void

  13. */

  14. public function up()

  15. {

  16. Schema::create('password_resets', function (Blueprint $table) {

  17. $table->string('email')->index();

  18. $table->string('token');

  19. $table->timestamp('created_at')->nullable();

  20. });

  21. }

  22.  
  23. /**

  24. * Reverse the migrations.

  25. *

  26. * @return void

  27. */

  28. public function down()

  29. {

  30. Schema::dropIfExists('password_resets');

  31. }

  32. }

运行 php artisan migrate 生成数据库

配置 路由

新建 lumen5.6/routes/api.php

 
  1. <?php

  2.  
  3. Route::group([

  4. 'middleware' => 'api', //这个本来用来实现api接口的处理,暂未用到

  5. 'prefix' => 'auth'

  6. ], function ($app) {

  7. $app->post('register', 'Auth\AuthController@register'); //注册

  8. $app->post('login', 'Auth\AuthController@login'); //登录

  9. $app->post('logout', 'Auth\AuthController@logout'); //登出

  10. $app->post('refresh', 'Auth\AuthController@refresh'); //刷新token

  11. $app->post('me', 'Auth\AuthController@me'); //获取个人信息

  12. });

  13.  
  14. Route::group(['middleware'=>'refresh.token'],function($app){

  15. $app->get('profile','User\UserController@profile'); //个人中心

  16. });

配置 guard

新建 lumen5.6/config/auth.php

 
  1. <?php

  2.  
  3. return [

  4.  
  5. /*

  6. |--------------------------------------------------------------------------

  7. | Authentication Defaults

  8. |--------------------------------------------------------------------------

  9. |

  10. | This option controls the default authentication "guard" and password

  11. | reset options for your application. You may change these defaults

  12. | as required, but they're a perfect start for most applications.

  13. |

  14. */

  15.  
  16. 'defaults' => [

  17. 'guard' => env('AUTH_GUARD', 'api'),

  18. 'passwords' => 'users'

  19. ],

  20.  
  21. /*

  22. |--------------------------------------------------------------------------

  23. | Authentication Guards

  24. |--------------------------------------------------------------------------

  25. |

  26. | Next, you may define every authentication guard for your application.

  27. | Of course, a great default configuration has been defined for you

  28. | here which uses session storage and the Eloquent user provider.

  29. |

  30. | All authentication drivers have a user provider. This defines how the

  31. | users are actually retrieved out of your database or other storage

  32. | mechanisms used by this application to persist your user's data.

  33. |

  34. | Supported: "token"

  35. |

  36. */

  37.  
  38. 'guards' => [

  39. 'api' => [

  40. 'driver' => 'jwt',

  41. 'provider' => 'users'

  42. ],

  43. ],

  44.  
  45. /*

  46. |--------------------------------------------------------------------------

  47. | User Providers

  48. |--------------------------------------------------------------------------

  49. |

  50. | All authentication drivers have a user provider. This defines how the

  51. | users are actually retrieved out of your database or other storage

  52. | mechanisms used by this application to persist your user's data.

  53. |

  54. | If you have multiple user tables or models you may configure multiple

  55. | sources which represent each model / table. These sources may then

  56. | be assigned to any extra authentication guards you have defined.

  57. |

  58. | Supported: "database", "eloquent"

  59. |

  60. */

  61.  
  62. 'providers' => [

  63. 'users' => [

  64. 'driver' => 'eloquent' ,

  65. 'model' => App\User::class,

  66. ]

  67. ],

  68.  
  69. /*

  70. |--------------------------------------------------------------------------

  71. | Resetting Passwords

  72. |--------------------------------------------------------------------------

  73. |

  74. | Here you may set the options for resetting passwords including the view

  75. | that is your password reset e-mail. You may also set the name of the

  76. | table that maintains all of the reset tokens for your application.

  77. |

  78. | You may specify multiple password reset configurations if you have more

  79. | than one user table or model in the application and you want to have

  80. | separate password reset settings based on the specific user types.

  81. |

  82. | The expire time is the number of minutes that the reset token should be

  83. | considered valid. This security feature keeps tokens short-lived so

  84. | they have less time to be guessed. You may change this as needed.

  85. |

  86. */

  87.  
  88. 'passwords' => [

  89. //

  90. ],

  91.  
  92. ];

配置 app.php

lumen5.6/bootstrap/app.php

 
  1. <?php

  2.  
  3. require_once __DIR__.'/../vendor/autoload.php';

  4.  
  5. try {

  6. (new Dotenv\Dotenv(__DIR__.'/../'))->load();

  7. } catch (Dotenv\Exception\InvalidPathException $e) {

  8. //

  9. }

  10.  
  11. /*

  12. |--------------------------------------------------------------------------

  13. | Create The Application

  14. |--------------------------------------------------------------------------

  15. |

  16. | Here we will load the environment and create the application instance

  17. | that serves as the central piece of this framework. We'll use this

  18. | application as an "IoC" container and router for this framework.

  19. |

  20. */

  21.  
  22. $app = new Laravel\Lumen\Application(

  23. realpath(__DIR__.'/../')

  24. );

  25.  
  26. #官方好像没有这一步,但是使用lumen这步也是需要注意的,我是添加了这行,因为我沿用laravel的目录风格

  27. $app->configure('auth');

  28. //取消下面2个的注释

  29. $app->withFacades();

  30. $app->withEloquent();

  31.  
  32. /*

  33. |--------------------------------------------------------------------------

  34. | Register Container Bindings

  35. |--------------------------------------------------------------------------

  36. |

  37. | Now we will register a few bindings in the service container. We will

  38. | register the exception handler and the console kernel. You may add

  39. | your own bindings here if you like or you can make another file.

  40. |

  41. */

  42.  
  43. $app->singleton(

  44. Illuminate\Contracts\Debug\ExceptionHandler::class,

  45. App\Exceptions\Handler::class

  46. );

  47.  
  48. $app->singleton(

  49. Illuminate\Contracts\Console\Kernel::class,

  50. App\Console\Kernel::class

  51. );

  52.  
  53. /*

  54. |--------------------------------------------------------------------------

  55. | Register Middleware

  56. |--------------------------------------------------------------------------

  57. |

  58. | Next, we will register the middleware with the application. These can

  59. | be global middleware that run before and after each request into a

  60. | route or middleware that'll be assigned to some specific routes.

  61. |

  62. */

  63.  
  64. // $app->middleware([

  65. // App\Http\Middleware\ExampleMiddleware::class

  66. // ]);

  67.  
  68. $app->routeMiddleware([

  69. 'refresh.token' => App\Http\Middleware\RefreshToken::class,

  70. 'api' => App\Http\Middleware\Api::class,

  71. 'auth' => App\Http\Middleware\Authenticate::class,

  72. ]);

  73.  
  74. /*

  75. |--------------------------------------------------------------------------

  76. | Register Service Providers

  77. |--------------------------------------------------------------------------

  78. |

  79. | Here we will register all of the application's service providers which

  80. | are used to bind services into the container. Service providers are

  81. | totally optional, so you are not required to uncomment this line.

  82. |

  83. */

  84.  
  85. $app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);

  86. $app->register(App\Providers\AppServiceProvider::class);

  87. $app->register(App\Providers\AuthServiceProvider::class);

  88. // $app->register(App\Providers\EventServiceProvider::class);

  89.  
  90. /*

  91. |--------------------------------------------------------------------------

  92. | Load The Application Routes

  93. |--------------------------------------------------------------------------

  94. |

  95. | Next we will include the routes file so that they can all be added to

  96. | the application. This will provide all of the URLs the application

  97. | can respond to, as well as the controllers that may handle them.

  98. |

  99. */

  100.  
  101. $app->router->group([

  102. 'namespace' => 'App\Http\Controllers',

  103. ], function ($router) {

  104. require __DIR__.'/../routes/web.php';

  105. require __DIR__.'/../routes/api.php';

  106. });

  107.  
  108. return $app;

配置 助手函数

新建 lumen5.6/app/helpers.php

 
  1. <?php

  2. /**

  3. * Created by IntelliJ IDEA.

  4. * User: Administrator

  5. * Date: 2018-08-01

  6. * Time: 下午 4:28

  7. */

  8. use Illuminate\Contracts\Auth\Factory as AuthFactory;

  9.  
  10. if(!function_exists('config_path')){

  11. /**

  12. * @description get the configuration path

  13. *

  14. * @param string $path

  15. * @return string

  16. * @author guilong

  17. * @date 2018-08-01

  18. */

  19. function config_path($path = ''){

  20. return app()->basePath().'/config'.($path ? '/' . $path : $path);

  21. }

  22. }

  23.  
  24. if (! function_exists('bcrypt')) {

  25. /**

  26. * Hash the given value against the bcrypt algorithm.

  27. *

  28. * @param string $value

  29. * @param array $options

  30. * @return string

  31. */

  32. function bcrypt($value, $options = [])

  33. {

  34. return app('hash')->driver('bcrypt')->make($value, $options);

  35. }

  36. }

  37.  
  38. if (! function_exists('request')) {

  39. /**

  40. * Get an instance of the current request or an input item from the request.

  41. *

  42. * @param array|string $key

  43. * @param mixed $default

  44. * @return \Illuminate\Http\Request|string|array

  45. */

  46. function request($key = null, $default = null)

  47. {

  48. if (is_null($key)) {

  49. return app('request');

  50. }

  51.  
  52. if (is_array($key)) {

  53. return app('request')->only($key);

  54. }

  55.  
  56. $value = app('request')->__get($key);

  57.  
  58. return is_null($value) ? value($default) : $value;

  59. }

  60. }

  61.  
  62. if (! function_exists('auth')) {

  63. /**

  64. * Get the available auth instance.

  65. *

  66. * @param string|null $guard

  67. * @return \Illuminate\Contracts\Auth\Factory|\Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard

  68. */

  69. function auth($guard = null)

  70. {

  71. if (is_null($guard)) {

  72. return app(AuthFactory::class);

  73. }

  74.  
  75. return app(AuthFactory::class)->guard($guard);

  76. }

  77. }

配置 用户模型

 
  1. <?php

  2.  
  3. namespace App;

  4.  
  5. use Tymon\JWTAuth\Contracts\JWTSubject;

  6. //use Illuminate\Notifications\Notifiable;

  7. //use Illuminate\Foundation\Auth\User as Authenticatable;

  8. use Laravel\Lumen\Auth\Authorizable;

  9.  
  10. use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;

  11. use Illuminate\Auth\Authenticatable;

  12. use Illuminate\Database\Eloquent\Model;

  13.  
  14. class User extends Model implements AuthenticatableContract, JWTSubject

  15. {

  16. protected $table = 'users';

  17. // use Notifiable;

  18. use Authenticatable;

  19.  
  20. protected $fillable = [

  21. 'email','name','password','api_token'

  22. ];

  23.  
  24. // Rest omitted for brevity

  25.  
  26. /**

  27. * Get the identifier that will be stored in the subject claim of the JWT.

  28. *

  29. * @return mixed

  30. */

  31. public function getJWTIdentifier()

  32. {

  33. return $this->getKey();

  34. }

  35.  
  36. /**

  37. * Return a key value array, containing any custom claims to be added to the JWT.

  38. *

  39. * @return array

  40. */

  41. public function getJWTCustomClaims()

  42. {

  43. return [];

  44. }

  45. }

配置handle 错误处理

lumen5.6/app/Exceptions/Handler.php

 
  1. <?php

  2.  
  3. namespace App\Exceptions;

  4.  
  5. use Exception;

  6. use Illuminate\Validation\ValidationException;

  7. use Illuminate\Auth\Access\AuthorizationException;

  8. use Illuminate\Database\Eloquent\ModelNotFoundException;

  9. use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;

  10. use Symfony\Component\HttpKernel\Exception\HttpException;

  11. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

  12.  
  13. class Handler extends ExceptionHandler

  14. {

  15. /**

  16. * A list of the exception types that should not be reported.

  17. *

  18. * @var array

  19. */

  20. protected $dontReport = [

  21. AuthorizationException::class,

  22. HttpException::class,

  23. ModelNotFoundException::class,

  24. ValidationException::class,

  25. ];

  26.  
  27. /**

  28. * Report or log an exception.

  29. *

  30. * This is a great spot to send exceptions to Sentry, Bugsnag, etc.

  31. *

  32. * @param \Exception $e

  33. * @return void

  34. */

  35. public function report(Exception $e)

  36. {

  37. parent::report($e);

  38. }

  39.  
  40. /**

  41. * Render an exception into an HTTP response.

  42. *

  43. * @param \Illuminate\Http\Request $request

  44. * @param \Exception $e

  45. * @return \Illuminate\Http\Response

  46. */

  47. public function render($request, Exception $e)

  48. {

  49. //参数验证错误的异常,我们需要返回400 的http code 和一句错误信息

  50. if($e instanceof ValidationException){

  51. return response(['error'=>array_first(array_collapse($e->errors()))],400);

  52. }

  53. //用户认证的异常,我们需要返回401的 http code 和错误信息

  54. if($e instanceof UnauthorizedHttpException){

  55. return response($e->getMessage(),401);

  56. }

  57.  
  58. //http错误,返回404 错误

  59. if($e instanceof HttpException){

  60. return response($e->getMessage(),404);

  61. }

  62.  
  63.  
  64. return parent::render($request, $e);

  65. }

  66. }

配置中间件

新建 lumen5.6/app/Http/Middleware/Api.php

 
  1. <?php

  2.  
  3. namespace App\Http\Middleware;

  4.  
  5. use Closure;

  6. use Illuminate\Contracts\Auth\Factory as Auth;

  7.  
  8. class Api

  9. {

  10. /**

  11. * The authentication guard factory instance.

  12. *

  13. * @var \Illuminate\Contracts\Auth\Factory

  14. */

  15. protected $auth;

  16.  
  17. /**

  18. * Create a new middleware instance.

  19. *

  20. * @param \Illuminate\Contracts\Auth\Factory $auth

  21. * @return void

  22. */

  23. public function __construct(Auth $auth)

  24. {

  25. $this->auth = $auth;

  26. }

  27.  
  28. /**

  29. * Handle an incoming request.

  30. *

  31. * @param \Illuminate\Http\Request $request

  32. * @param \Closure $next

  33. * @param string|null $guard

  34. * @return mixed

  35. */

  36. public function handle($request, Closure $next, $guard = null)

  37. {

  38. if ($this->auth->guard($guard)->guest()) {

  39. // return response('Unauthorized.', 401);

  40. }

  41. return $next($request);

  42. }

  43. }

新建 lumen5.6/app/Http/Middleware/RefreshToken.php

 
  1. <?php

  2.  
  3. namespace App\Http\Middleware;

  4.  
  5. use Illuminate\Support\Facades\Auth;

  6. use Closure;

  7. use Tymon\JWTAuth\Exceptions\JWTException;

  8. use Tymon\JWTAuth\Exceptions\TokenExpiredException;

  9. use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

  10. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

  11.  
  12. class RefreshToken extends BaseMiddleware

  13. {

  14.  
  15. /**

  16. * Handle an incoming request.

  17. *

  18. * @param \Illuminate\Http\Request $request

  19. * @param \Closure $next

  20. * @param string|null $guard

  21. * @return mixed

  22. */

  23. public function handle($request, Closure $next, $guard = null)

  24. {

  25. //检查此次请求汇总是否带有token ,如果没有则抛出异常

  26. $this->checkForToken($request);

  27.  
  28. try{

  29. //检查用户的登录状态,如果正常则通过

  30. if($this->auth->parseToken()->authenticate()){

  31. return $next($request);

  32. }

  33.  
  34. throw new UnauthorizedHttpException('jwt-auth','未登录');

  35. }

  36. catch(TokenExpiredException $e){

  37. //此处捕获到了token 过期所抛出的 tokenexpiredexception 异常,我们在这里需要做的是刷新该用户的token

  38. try{

  39. //刷新用户的token

  40. $token = $this->auth->refresh();

  41.  
  42. //使用一次性登录以保证此处请求的成功

  43. Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);

  44. }

  45. catch(JWTException $e){

  46. //如果捕获到了异常,即代表refresh 也过期了 ,用户无法刷新令牌 ,需要重新登录

  47. throw new UnauthorizedHttpException('jwt-auth',$e->getMessage());

  48. }

  49. }

  50. //在响应头中返回新的token

  51. return $this->setAuthenticationHeader($next($request),$token);

  52. }

  53. }

配置控制器

新建 lumen5.6/app/Http/Controllers/Auth/AuthController.php

 
  1. <?php

  2.  
  3. namespace App\Http\Controllers\Auth;

  4.  
  5. use App\Http\Controllers\Controller;

  6. use Illuminate\Support\Facades\Auth;

  7. use Illuminate\Support\Facades\Validator;

  8. use Exception;

  9. use Tymon\JWTAuth\Facades\JWTAuth;

  10.  
  11. class AuthController extends Controller

  12. {

  13. private $rule = [

  14. 'email' => 'required|email|max:255|unique:users',

  15. 'password' => 'required',

  16. 'name' => 'required',

  17. ];

  18.  
  19. private $message = [

  20. 'name.required' => '姓名必须',

  21. 'email.required' => '邮箱必须',

  22. 'email.email' => '邮箱格式不正确',

  23. 'email.max' => '邮箱最大255个字',

  24. 'email.unique' => '该邮箱已存在',

  25. 'password.required' => '密码必须',

  26. ];

  27.  
  28. /**

  29. * Create a new controller instance.

  30. *

  31. * @return void

  32. */

  33. public function __construct()

  34. {

  35. //在 Authenticate 里 使用 guard => api 验证用户信息

  36. $this->middleware('auth:api',['except'=>['login','register']]);

  37. }

  38.  
  39. /**

  40. * @description register user

  41. *

  42. * @param

  43. * @return

  44. * @author guilong

  45. * @date 2018-08-02

  46. */

  47. public function register(){

  48.  
  49. //直接输出错误

  50. // $this->validate($request, $this->rule,$this->message);

  51. // 捕获错误

  52. $validator = Validator::make(request()->all(), $this->rule,$this->message);

  53. if($validator->fails()){

  54. $messages = $validator->errors();

  55. return response()->json([

  56. 'code' => 501,

  57. 'msg' => $messages->first()

  58. ]);

  59. }

  60.  
  61. $user = [

  62. 'email' => request()->input('email'),

  63. 'name' => request()->input('name'),

  64. 'password' => bcrypt(request()->input('password')),

  65. ];

  66. try{

  67. //插入数据库

  68. $user_info = \App\User::create($user);

  69. //获取token

  70. $token = JWTAuth::fromUser($user_info);

  71. //更新token

  72. \App\User::where('id','=',$user_info['id'])->update(['api_token'=>$token]);

  73.  
  74.  
  75. }

  76. catch(Exception $e){

  77. // var_dump($e->getMessage());

  78. // var_dump($e->getCode());

  79. return response()->json([

  80. 'code' => 502,

  81. 'msg' => $this->message['email.unique']

  82. ]);

  83. }

  84.  
  85. return response()->json([

  86. 'code' => 200,

  87. 'msg' => '',

  88. 'access_token' => $token

  89. ]);

  90. }

  91.  
  92. public function login(){

  93. //直接输出错误

  94. // $this->validate($request, $this->rule,$this->message);

  95. // 捕获错误

  96. $validator = Validator::make(request()->all(), ['email'=>'required|email|max:255','password'=>$this->rule['password']],$this->message);

  97. if($validator->fails()){

  98. $messages = $validator->errors();

  99. return response()->json([

  100. 'code' => 501,

  101. 'msg' => $messages->first()

  102. ]);

  103. }

  104.  
  105. $credentials = request(['email','password']);

  106.  
  107. if(! $token = auth()->attempt($credentials)){

  108. return response()->json([

  109. 'code' => 401,

  110. 'msg' => '登录失败'

  111. ]);

  112. }

  113.  
  114. return response()->json([

  115. 'code' => 200,

  116. 'msg' => '',

  117. 'data' => [

  118. 'access_token' => $token,

  119. 'token_type' => 'bearer',

  120. 'expires_in' => auth()->factory()->getTTL()*60

  121. ]

  122. ]);

  123. }

  124.  
  125. public function me(){

  126.  
  127. try {

  128. $user = auth()->userOrFail();

  129. } catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {

  130. return response()->json([

  131. 'code' => 401,

  132. 'msg' => '登录失败',

  133. ]);

  134. }

  135.  
  136. return response()->json([

  137. 'code' => 200,

  138. 'msg' => '',

  139. 'data' => $user,

  140. ]);

  141. }

  142.  
  143. public function logout(){

  144. auth()->logout();

  145.  
  146. return response()->json([

  147. 'code' => 200,

  148. 'msg' => 'logged out',

  149. ]);

  150. }

  151.  
  152. public function refresh(){

  153. return response()->json([

  154. 'code' => 200,

  155. 'msg' => '',

  156. 'data' => [

  157. 'access_token' => auth()->refresh(),

  158. 'token_type' => 'bearer',

  159. 'expires_in' => auth()->factory()->getTTL()*60

  160. ]

  161. ]);

  162. }

  163.  
  164.  
  165. }

新建 lumen5.6/app/Http/Controllers/User/UserController.php

 
  1. <?php

  2.  
  3. namespace App\Http\Controllers\User;

  4.  
  5. use App\Http\Controllers\Controller;

  6.  
  7. class UserController extends Controller

  8. {

  9. /**

  10. * Create a new controller instance.

  11. *

  12. * @return void

  13. */

  14. public function __construct()

  15. {

  16. $this->middleware('auth:api');

  17. }

  18.  
  19. public function profile(){

  20. try {

  21. $user = auth()->userOrFail();

  22. } catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {

  23. return response()->json([

  24. 'code' => 401,

  25. 'msg' => '登录失败',

  26. ]);

  27. }

  28.  
  29. return response()->json([

  30. 'code' => 200,

  31. 'msg' => '',

  32. 'data' => $user,

  33. ]);

  34. }

  35. }

最后配置 composer.json

 
  1. //在 autoload 里加入 files 这一段

  2.  
  3. "autoload": {

  4. "psr-4": {

  5. "App\\": "app/"

  6. },

  7. "files":[

  8. "app/helpers.php"

  9. ]

  10. },

运行 composer dumpauto 命令, 更新自动运行文件

目录结构如下:

生成密钥

jwt-auth 已经预先定义好了一个 Artisan 命令方便你生成 Secret,你只需要在你的 shell 中运行如下命令即可:

shell

$ php artisan jwt:secret

此命令会在你的 .env 文件中新增一行 JWT_SECRET=secret

 

用postman请求接口测试

注册请求:

登录请求:

个人信息请求 post => me:

个人信息请求 get => profile:

如图可以看到我们已经拿到了新的 token,接下来的事情便会交由我们前面设置的 axios 拦截器处理,它会将本地的 token 替换为此 token。
版本科普

感觉蛮多人对版本没什么概念,所以在这里科普下常见的版本。

    α(Alpha)版

    ​ 这个版本表示该 Package 仅仅是一个初步完成品,通常只在开发者内部交流,也有很少一部分发布给专业测试人员。一般而言,该版本软件的 Bug 较多,普通用户最好不要安装。
    β(Beta)版

    该版本相对于 α(Alpha)版已有了很大的改进,修复了严重的错误,但还是存在着一些缺陷,需要经过大规模的发布测试来进一步消除。通过一些专业爱好者的测试,将结果反馈给开发者,开发者们再进行有针对性的修改。该版本也不适合一般用户安装。
    RC/ Preview版

    RC 即 Release Candidate 的缩写,作为一个固定术语,意味着最终版本准备就绪。一般来说 RC 版本已经完成全部功能并清除大部分的 BUG。一般到了这个阶段 Package 的作者只会修复 Bug,不会对软件做任何大的更改。
    普通发行版本

    一般在经历了上面三个版本后,作者会推出此版本。此版本修复了绝大部分的 Bug,并且会维护一定的时间。(时间根据作者的意愿而决定,例如 Laravel 的一般发行版本会提供为期一年的维护支持。)
    LTS(Long Term Support) 版

    该版本是一个特殊的版本,和普通版本旨在支持比正常时间更长的时间。(例如 Laravel 的 LTS 版本会提供为期三年的 维护支持。)

 
  • //在响应头中返回新的token

  • return $this->setAuthenticationHeader($next($request),$token)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Lumen是一个基于Laravel框架的微型PHP框架,它可以用于构建轻量级的API服务。而Dingo是一个在Laravel框架上构建API的工具包。JWT(JSON Web Token)是一种用于进行身份验证和授权的开放标准。 在使用Lumen结合Dingo和JWT进行开发时,需要先安装Lumen服务提供者、JWT和Dingo的组件。可以使用Composer来管理这些依赖。确保你的电脑上安装了Composer。 在Lumen中,你可以使用控制器来处理请求。引用是一个示例UserController。在这个控制器中,我们注入了JWTAuth实例,并使用它来处理用户的登录请求。其中,我们首先获取请求中的参数,然后使用这些参数进行条件查询。如果登录认证成功,我们会返回一个包含JWT令牌的JSON响应。 对于跨域问题,你可以使用palanik/lumen-cors来解决。引用提供了安装和配置palanik/lumen-cors的方法。你需要通过Composer来安装该组件,并在bootstrap/app.php文件中添加cors路由中间件。 以上就是关于Lumen、Dingo和JWT的一些基本信息和配置方法。如果你有关于它们的更具体的问题,请告诉我。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Lumen 配合 JWT + Dingo 开发流程](https://blog.csdn.net/qq_44149053/article/details/89444892)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *3* [lumen+dingo+jwt搭建api系统](https://blog.csdn.net/Chenlevin/article/details/111830096)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值