一.安装
我们使用Composer安装jwt扩展包:
- composer require tymon/jwt-auth 0.5.*
二.配置
安装完成后,需要在 config/app.php 中注册相应的服务提供者:
- Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class
然后注册需要用到的对应门面:
- 'aliases' => [
- 'JWTAuth'=> Tymon\JWTAuth\Facades\JWTAuth::class,
- 'JWTFactory'=> Tymon\JWTAuth\Facades\JWTFactory::class,
- ],
然后发布相应配置文件:
- php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
最后生成密钥:
在 /app/Http/Kernel.php 中 $routeMiddleware 添加
- 'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
- 'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
需要在路由组添加 :
- ['middleware' => ['jwt.auth','jwt.refresh']
其实,这是Jwt-auth 的默认中间件(Middleware)在处理身份认证。按其文档说明:我们可以在 /app/Exceptions/Handler.php 中可以进行异常判断。但有可能并没有效果。这种情况下,我们可以自己去添加一个中间件处理身份认证。
1、添加一个 Middleware
可以使用命令行添加:php artisan make:middleware GetUserFromToken 此命令将会 在 app/Http/Middleware 目录内置立一个名称GetUserFromToken 的类。
2、在 GetUserFromToken 中编辑代码
- <?php
-
- namespace App\Http\Middleware;
-
- use Closure;
- use JWTAuth;
- use Tymon\JWTAuth\Exceptions\JWTException;
- use Tymon\JWTAuth\Exceptions\TokenExpiredException;
- use Tymon\JWTAuth\Exceptions\TokenInvalidException;
-
- class GetUserFromToken
- {
- /**
- * @param \Illuminate\Http\Request $request
- * @param \Closure $next
- * @return mixed
- */
- public function handle($request, Closure $next)
- {
- try {
-
- if (! $user = JWTAuth::parseToken()->authenticate()) {
- return response()->json([
- 'errcode' => 400004,
- 'errmsg' => 'user not found'
- ], 404);
- }
-
- } catch (TokenExpiredException $e) {
-
- return response()->json([
- 'errcode' => 400001,
- 'errmsg' => 'token expired'
- ], $e->getStatusCode());
-
- } catch (TokenInvalidException $e) {
-
- return response()->json([
- 'errcode' => 400003,
- 'errmsg' => 'token invalid'
- ], $e->getStatusCode());
-
- } catch (JWTException $e) {
-
- return response()->json([
- 'errcode' => 400002,
- 'errmsg' => 'token absent'
- ], $e->getStatusCode());
-
- }
- return $next($request);
- }
- }
3、在 /app/Http/Kernel.php 中 $routeMiddleware 新增 内容
- protected $routeMiddleware = [
- 'auth' => \App\Http\Middleware\Authenticate::class,
- 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
- 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
- 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
- 'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
- 'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
- 'jwt.api.auth' => \App\Http\Middleware\GetUserFromToken::class, //新增注册的中间件
- ];
4、在路由中指定使用 jwt.api.auth
- ['middleware' => 'jwt.api.auth']
-
来自
http://blog.csdn.net/rorntuck7/article/details/52330119