laravel安装jwt-auth及验证(实例)

laravel 安装jwt-auth及验证php

 

一、使用composer安装jwt,cmd到项目文件夹中;node

composer require tymon/jwt-auth 1.0.*(这里版本号根据本身的须要写)laravel

安装jwt ,参考官方文档web

二、若是laravel版本低于5.4json

打开根目录下的config/app.phpapi

在'providers'数组里加上Tymon\JWTAuth\Providers\LaravelServiceProvider::class,数组

'providers' => [ ... Tymon\JWTAuth\Providers\LaravelServiceProvider::class,]安全

三、在 config 下增长一个 jwt.php 的配置文件session

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"架构

四、在 .env 文件下生成一个加密密钥,如:JWT_SECRET=foobar

php artisan jwt:secret

五、在user模型中写入下列代码

<?php
namespace App\Model;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
 // Rest omitted for brevity
 protected $table="user";
 public $timestamps = false;
 public function getJWTIdentifier()
 {
 return $this->getKey();
 }
 public function getJWTCustomClaims()
 {
 return [];
 }
}

  

六、注册两个 Facade

config/app.php

'aliases' => [
 ...
 // 添加如下两行
 'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth',
 'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory',
],

  

七、修改 auth.php

config/auth.php

'guards' => [
 'web' => [
 'driver' => 'session',
 'provider' => 'users',
 ],
 'api' => [
 'driver' => 'jwt',      // 原来是 token 改为jwt
 'provider' => 'users',
 ],
],

  

八、注册路由

Route::group([
 'prefix' => 'auth'
], function ($router) {
 $router->post('login', 'AuthController@login');
 $router->post('logout', 'AuthController@logout');
});

  

九、建立token控制器

php artisan make:controller AuthController

代码以下:

<?php
namespace App\Http\Controllers;
use App\Model\User;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
class AuthController extends Controller
{
 /**
 * Create a new AuthController instance.
 *
 * @return void
 */
 public function __construct()
 {
 $this->middleware('auth:api', ['except' => ['login']]);
 }
 /**
 * Get a JWT via given credentials.
 *
 * @return \Illuminate\Http\JsonResponse
 */
 public function login()
 {
 $credentials = request(['email', 'password']);
 if (! $token = auth('api')->attempt($credentials)) {
 return response()->json(['error' => 'Unauthorized'], 401);
 }
 return $this->respondWithToken($token);
 }
 /**
 * Get the authenticated User.
 *
 * @return \Illuminate\Http\JsonResponse
 */
 public function me()
 {
 return response()->json(JWTAuth::parseToken()->touser());
 }
 /**
 * Log the user out (Invalidate the token).
 *
 * @return \Illuminate\Http\JsonResponse
 */
 public function logout()
 {
 JWTAuth::parseToken()->invalidate();
 return response()->json(['message' => 'Successfully logged out']);
 }
 /**
 * Refresh a token.
 *
 * @return \Illuminate\Http\JsonResponse
 */
 public function refresh()
 {
 return $this->respondWithToken(JWTAuth::parseToken()->refresh());
 }
 /**
 * Get the token array structure.
 *
 * @param  string $token
 *
 * @return \Illuminate\Http\JsonResponse
 */
 protected function respondWithToken($token)
 {
 return response()->json([
 'access_token' => $token,
 'token_type' => 'bearer',
 'expires_in' => JWTAuth::factory()->getTTL() * 60
 ]);
 }
}

  

注意:attempt 一直返回false,是由于password被加密了,使用bcrypt或者password_hash加密后就能够了

十、验证token获取用户信息

有两种使用方法:

加到 url 中:?token=你的token

加到 header 中,建议用这种,由于在 https 状况下更安全:Authorization:Bearer 你的token

十一、首先使用artisan命令生成一个中间件,我这里命名为RefreshToken.php,建立成功后,须要继承一下JWT的BaseMiddleware

代码以下:

<?php
namespace App\Http\Middleware;
use Auth;
use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
// 注意,咱们要继承的是 jwt 的 BaseMiddleware
class RefreshToken extends BaseMiddleware
{
 /**
 * Handle an incoming request.
 *
 * @ param  \Illuminate\Http\Request $request
 * @ param  \Closure $next
 *
 * @ throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
 *
 * @ return mixed
 */
 public function handle($request, Closure $next)
 {
 // 检查这次请求中是否带有 token,若是没有则抛出异常。
 $this->checkForToken($request);
 // 使用 try 包裹,以捕捉 token 过时所抛出的 TokenExpiredException  异常
 try {
 // 检测用户的登陆状态,若是正常则经过
 if ($this->auth->parseToken()->authenticate()) {
 return $next($request);
 }
 throw new UnauthorizedHttpException('jwt-auth', '未登陆');
 } catch (TokenExpiredException $exception) {
 // 此处捕获到了 token 过时所抛出的 TokenExpiredException 异常,咱们在这里须要作的是刷新该用户的 token 并将它添加到响应头中
 try {
 // 刷新用户的 token
 $token = $this->auth->refresh();
 // 使用一次性登陆以保证这次请求的成功
 Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
 } catch (JWTException $exception) {
 // 若是捕获到此异常,即表明 refresh 也过时了,用户没法刷新令牌,须要从新登陆。
 throw new UnauthorizedHttpException('jwt-auth', $exception->getMessage());
 }
 }
 // 在响应头中返回新的 token
 return $this->setAuthenticationHeader($next($request), $token);
 }
}

  

这里主要须要说的就是在token进行刷新后,不但须要将token放在返回头中,最好也将请求头中的token进行置换,由于刷新事后,请求头中的token就已经失效了,若是接口内的业务逻辑使用到了请求头中的token,那么就会产生问题。

这里使用

$request->headers->set('Authorization','Bearer '.$token);

  

将token在请求头中刷新。

建立而且写完中间件后,只要将中间件注册,而且在App\Exceptions\Handler.php内加上一些异常处理就ok了。

十二、kernel.php文件中

$routeMiddleware 添加中间件配置

'RefreshToken' => \App\Http\Middleware\RefreshToken::class,

  

1三、添加路由

Route::group(['prefix' => 'user'],function($router) {
 $router->get('userInfo','UserController@userInfo')->middleware('RefreshToken');
});

  

在控制器中经过 JWTAuth::user();就能够获取用户信息

更多PHP内容请访问:

腾讯T3-T4标准精品PHP架构师教程目录大全,只要你看完保证薪资上升一个台阶(持续更新)

相关文章
相关标签/搜索