官方文档:
注意:
Laravel 5.5
已经不能再使用jwt-auth 0.5.*
等版本了,请使用最新版本,当前最新版为tymon/jwt-auth: 1.0.0-rc.1
一 安装
-
通过
composer
安装composer require tymon/jwt-auth
通过该命令安装的可能为 0.5.* 版本,执行上述命令后可按照下面所述升级版本:
参考:
在
composer.json
文件中将tymon/jwt-auth
版本修改为1.0.0-rc.1
:"tymon/jwt-auth": "^1.0.0-rc.1"
-
执行
composer update
-
添加到
provider
添加
service provider
到config/app.php
文件的providers
数组中:'providers' => [ ... Tymon\JWTAuth\Providers\LaravelServiceProvider::class, ]
-
发布配置
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
执行后会在
config
目录下生成jwt.php
文件 -
生成密钥
php artisan jwt:secret
执行后会在
.env
文件最后生成JWT_SECRET
,如:JWT_SECRET=158S2Rhux6DLJDwPVZdspU59c7YnIyBJ
二 使用
-
修改
User.php
让
User.php
实现Tymon\JWTAuth\Contracts\JWTSubject
类实现两个方法:
getJWTIdentifier()
和getJWTCustomClaims()
-
修改后的
User.php
如下:<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Tymon\JWTAuth\Contracts\JWTSubject; class User extends Authenticatable implements JWTSubject { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * Get the identifier that will be stored in the subject claim of the JWT. * * @return mixed */ public function getJWTIdentifier() { // TODO: Implement getJWTIdentifier() method. return $this->getKey(); } /** * Return a key value array, containing any custom claims to be added to the JWT. * * @return array */ public function getJWTCustomClaims() { // TODO: Implement getJWTCustomClaims() method. return []; } }
-
配置
auth.php
修改
config/auth.php
文件中default
及guards
如下:'defaults' => [ 'guard' => 'api', 'passwords' => 'users', ], ... 'guards' => [ 'api' => [ 'driver' => 'jwt', 'provider' => 'users', ], ],
-
添加路由
在
routes/api.php
中添加路由如下:Route::group([ 'middleware' => 'api', // 'namespace' => 'App\Http\Controllers',// 这一行不需要加,AuthController中已配置namespace,否则运行时会在App\Http\Controllers\App\Http\Controllers\AuthController 下寻找AuthController,从而报找不到控制器的错 'prefix' => 'auth' ], function ($router) { Route::post('login', 'AuthController@login'); Route::post('logout', 'AuthController@logout'); Route::post('refresh', 'AuthController@refresh'); Route::post('me', 'AuthController@me'); });
-
创建控制器
AuthController
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 { /** * AuthController constructor. */ 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'); $token = $this->guard()->attempt($credentials); if ($token) { 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(); } }
三 测试api
- 工程放到xmapp的
htdocs
目录下 - 使用Postman访问,地址:http://localhost/project-name/public/api/auth/login