我是靠谱客的博主 聪慧发箍,最近开发中收集的这篇文章主要介绍Lumen使用JWT,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Lumen使用JWT

  1. 进入项目,使用Composer安装 ‘tymon/jwt-auth’
composer require tymon/jwt-auth 1.*@rc
  1. 修改 ‘bootstrap’ 文件夹下的 ‘app.php’
    2.1取消以下代码的注释
$app->withFacades();
$app->withEloquent();
$app->routeMiddleware([
   'auth' => AppHttpMiddlewareAuthenticate::class,
]);
$app->register(AppProvidersAuthServiceProvider::class);

2.2增加JWT的注册

$app->register(TymonJWTAuthProvidersLumenServiceProvider::class);
  1. 修改 ‘config’ 文件夹下的 ‘auth.php’
'defaults' => [
      'guard' => 'api',
      'passwords' => 'users',
  ],
  'guards' => [
      'api' => [
          'driver' => 'jwt',                           
          'provider' => 'users',
      ],
  ],
  'providers' => [
      'users' => [
          'driver' => 'eloquent',
          'model'  => AppUser::class,        
      ],
  ],
  1. 修改 ‘app/Middleware’ 文件夹下的 ‘Authenticate.php’
public function handle($request, Closure $next, $guard = null)
   {
       if ($this->auth->guard($guard)->guest()) {
           return response('Unauthorized.', 401);
       }

       return $next($request);
   }
  1. 修改 ‘app/Models’ 文件夹下的 'User.php’
    5.1 引入JWT
use TymonJWTAuthContractsJWTSubject;

5.2 实现JWTSubject接口

class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject

5.3 添加方法

   /**
    * JWT
    *
    * @author AdamTyn
    */
   public function getJWTIdentifier()
   {
       return $this->getKey();
   }

   /**
    * JWT
    *
    * @author AdamTyn
    */
   public function getJWTCustomClaims()
   {
       return [];
   }
  1. ‘app/Http/Controller’ 文件夹下新建 'AuthController.php’,内容如下所示:
namespace AppHttpControllers;

use AppUser;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesHash;
use TymonJWTAuthJWTAuth;

class AuthController extends Controller
{
  protected $jwt;

  public function __construct(JWTAuth $jwt)
  {
      $this->jwt = $jwt;
  }
  
  /*登录*/
  public function login(Request $request)
  {
      $response = array('code' => '0');
      $user = User::where('username', $request->input('username'))
                      ->where('password', $request->input('password'))->first();
      if (!$token = Auth::login($user)) {
          return '系统错误,无法生成令牌';
      } else {
       	/*
         	user_id: strval($user->id)
         	token: $token
       	*/
          return '登录成功';
      }
  }
  
  /*用户登出*/
  public function logout()
  {
      $response = array('code' => '0');

      Auth::invalidate(true);

      return response()->json($response);
  }


  /*更新用户Token*/
  public function refreshToken()
  {

      $response = array('code' => '0');

      if (!$token = Auth::refresh(true, true)) {
          $response['code']     = '5000';
          $response['errorMsg'] = '系统错误,无法生成令牌';
      } else {
          $response['data']['access_token'] = $token;
          $response['data']['expires_in']   = strval(time() + 86400);
      }
  }

  /*登录后返回用户数据*/
  public function me()
  {
      return response()->json(auth()->user());
  }
}
  1. 添加路由,修改 ‘routes’ 文件夹下的 ‘web.php’
$router->post('login','AuthController@login');
$router->group(['prefix'=>'/','middleware'=>'auth:api'],function () use ($router){
   	$router->post('logout','AuthController@logout');
		$router->post('refresh','AuthController@refreshToken');
		$router->post('me','AuthController@me');
});
  1. 使用以下命令获取密钥
 php artisan jwt:secret

最后

以上就是聪慧发箍为你收集整理的Lumen使用JWT的全部内容,希望文章能够帮你解决Lumen使用JWT所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(41)

评论列表共有 0 条评论

立即
投稿
返回
顶部