Laravel10 tymon jwt-auth 的使用姿势

Laravel   2024-01-10 19:50   65   1  

安装

composer require tymon/jwt-auth

添加service provider

// config/app.php
'providers' => [

    ...

    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
];

发布配置

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

生成secret key

php artisan jwt:secret

调整UserModel

<?php
namespace App\Models;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject{
    use Notifiable;    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}

配置认证守卫

// config/auth.php
'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

    ...
    'guards' => [
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
    ],
],

配置路由

Route::group([
    'middleware' => 'api',
    'namespace' => 'App\Http\Controllers',
    'prefix' => 'auth'
], function ($router) {
    Route::post('login', 'AuthController@login');
    Route::post('logout', 'AuthController@logout');
    Route::post('refresh', 'AuthController@refresh');
    Route::post('me', 'AuthController@me');

});

创建控制器

// php artisan make:controller AuthController
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class AuthController extends Controller{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }
    /**
     * Get a JWT token via given credentials.
     *
     * @param  \Illuminate\Http\Request  $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');
        
        if ($token = $this->guard()->attempt($credentials)) {
            return $this->respondWithToken($token);
        }
        return response()->json(['error' => 'Unauthorized'], 401);
    }
        
    /**
     * Get the authenticated User
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json($this->guard()->user());
    }
    
    /**
     * Log the user out (Invalidate the token)
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        $this->guard()->logout();
        return response()->json(['message' => 'Successfully logged out']);
    }
        
    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken($this->guard()->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' => $this->guard()->factory()->getTTL() * 60
        ]);
    }
            
    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\Guard
     */
    public function guard()
    {
        return Auth::guard();
    }
}

创建认证中间件

// php artisan make:middleware JwtCheck

<?php

namespace App\Http\Middleware;

use App\Exceptions\ApiException;
use Closure;
use Exception;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;


class JwtCheck
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next)
    {
        // 从请求中获取 token,
        $token = $request->bearerToken();
        if (!$token) {
            throw new ApiException(40000, '用户信息不存在');
        }

        try {
            $auth = auth('api')->parseToken()->checkOrFail();
        } catch (TokenInvalidException $e) {
            throw new ApiException(40100, 'token信息不合法');
        } catch (TokenExpiredException $e) {
            throw new ApiException(40200, 'token已过期');
        } catch (Exception $e) {
            throw new ApiException(40300, '网络异常,请稍后重试');
        }

        return $next($request);
    }
}

参考

tymon/jwt-auth 文档

下一篇
没有了
博客评论
jiqimao
说:

测试回复内容

1
发表评论
说明:请文明发言,共建和谐网络,您的个人信息不会被公开显示。