Rumah  >  Artikel  >  rangka kerja php  >  laravel安装jwt-auth及验证(实例)

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

L
Lke hadapan
2020-05-28 10:37:325865semak imbas

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


laravel 安装jwt-auth及验证


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

composer require tymon/jwt-auth 1.0.*(这里版本号根据自己的需要写)

安装jwt ,参考官方文档https://jwt-auth.readthedocs.io/en/docs/laravel-installation/

2、如果laravel版本低于5.4

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

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

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

3、在 config 下增加一个 jwt.php 的配置文件

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

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

php artisan jwt:secret

5、在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 [];
    }
}

6、注册两个 Facade

config/app.php

&#39;aliases&#39; => [
        ...
        // 添加以下两行
        &#39;JWTAuth&#39; => &#39;Tymon\JWTAuth\Facades\JWTAuth&#39;,
        &#39;JWTFactory&#39; => &#39;Tymon\JWTAuth\Facades\JWTFactory&#39;,
],

7、修改 auth.php

config/auth.php

&#39;guards&#39; => [
    &#39;web&#39; => [
        &#39;driver&#39; => &#39;session&#39;,
        &#39;provider&#39; => &#39;users&#39;,
    ],
    &#39;api&#39; => [
        &#39;driver&#39; => &#39;jwt&#39;,      // 原来是 token 改成jwt
        &#39;provider&#39; => &#39;users&#39;,
    ],
],

8、注册路由

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

9、创建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(&#39;auth:api&#39;, [&#39;except&#39; => [&#39;login&#39;]]);
    }
    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request([&#39;email&#39;, &#39;password&#39;]);
        if (! $token = auth(&#39;api&#39;)->attempt($credentials)) {
            return response()->json([&#39;error&#39; => &#39;Unauthorized&#39;], 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([&#39;message&#39; => &#39;Successfully logged out&#39;]);
    }
    /**
     * 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([
            &#39;access_token&#39; => $token,
            &#39;token_type&#39; => &#39;bearer&#39;,
            &#39;expires_in&#39; => JWTAuth::factory()->getTTL() * 60
        ]);
    }
}

注意:attempt  一直返回false,是因为password被加密了,使用bcrypt或者password_hash加密后就可以了

10、验证token获取用户信息

有两种使用方法:

加到 url 中:?token=你的token

加到 header 中,建议用这种,因为在 https 情况下更安全:Authorization:Bearer 你的token

11、首先使用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(&#39;jwt-auth&#39;, &#39;未登录&#39;);
        } catch (TokenExpiredException $exception) {
            // 此处捕获到了 token 过期所抛出的 TokenExpiredException 异常,我们在这里需要做的是刷新该用户的 token 并将它添加到响应头中
            try {
                // 刷新用户的 token
                $token = $this->auth->refresh();
                // 使用一次性登录以保证此次请求的成功
                Auth::guard(&#39;api&#39;)->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()[&#39;sub&#39;]);
            } catch (JWTException $exception) {
                // 如果捕获到此异常,即代表 refresh 也过期了,用户无法刷新令牌,需要重新登录。
                throw new UnauthorizedHttpException(&#39;jwt-auth&#39;, $exception->getMessage());
            }
        }
        // 在响应头中返回新的 token
        return $this->setAuthenticationHeader($next($request), $token);
    }
}

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

这里使用

$request->headers->set(&#39;Authorization&#39;,&#39;Bearer &#39;.$token);

将token在请求头中刷新。

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

12、kernel.php文件中

$routeMiddleware 添加中间件配置

&#39;RefreshToken&#39; => \App\Http\Middleware\RefreshToken::class,

13、添加路由

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

在控制器中通过  JWTAuth::user();就可以获取用户信息

更多laravel框架技术文章,请访问laravel教程!

Atas ialah kandungan terperinci laravel安装jwt-auth及验证(实例). Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Artikel ini dikembalikan pada:csdn.net. Jika ada pelanggaran, sila hubungi admin@php.cn Padam