composer require tymon/jwt-auth
// config/app.php 'providers' => [ ... Tymon\JWTAuth\Providers\LaravelServiceProvider::class, ];
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret
<?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); } }
测试回复内容