https://learnku.com/articles/10885/full-use-of-jwtphp
安裝
composer.json的require中加入下面的包,composer installjson
"tymon/jwt-auth": "1.0.0-rc4.1"
在 config/app.php 中provider中添加 Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
在 config/app.php 中aliases中添加 'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class, 'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
發佈配置文件 php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" 生成密鑰 php artisan jwt:secret
使用
先引入下面內容:api
use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth;
config/auth.php api->driver=>'token',修改成'jwt' 'api' => [ 'driver' => 'jwt', 'provider' => 'users', ],
在exceptopns中的Handler 的render方法中加入下面代碼全局定義返回錯誤app
switch ($exception) { case ($exception instanceof AuthenticationException): return Response::error(401, $exception->getMessage()); case ($exception instanceof ValidationException): return Response::error(422, 'params error', ($exception->errors())); default: return Response::error(500, '未知錯誤'); } return parent::render($request, $exception);
將用戶模型關聯上composer
1. 經過token獲取用戶ide
JWTAuth::toUser( $tokenStr );
2. 經過用戶獲取tokenui
在須要的模型裏面添加this
在須要的模型裏面添加 use Tymon\JWTAuth\Contracts\JWTSubject; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable implements JWTSubject 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 []; } //在須要的地方使用下面的方法生成token $user = JWTAuth::fromUser( $model );
3. 使用負載(payload) 生成tokenurl
通常是不能用於登錄的(若是登錄的用戶生成的token,則能夠用於登錄)
// 建立負載 $customClaims = ['foo' => 'bar', 'baz' => 'bob']; $payload = JWTFactory::make($customClaims); $token = JWTAuth::encode($payload);
登陸.net
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 = JWTAuth::fromUser( $UserModel );這種也能夠 if ($token = $this->guard()->attempt($credentials)) { return $this->respondWithToken($token); } return response()->json(['error' => 'Unauthorized'], 401); }
4.退出
$this->guard()->logout(); 或 JWTAuth::parseToken()->invalidate();
5.刷新token
public function refresh() { return $this->respondWithToken($this->guard()->refresh()); }
6.返回token
protected function respondWithToken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', //過時時間 'expires_in' => $this->guard()->factory()->getTTL() * 60 ]); }
返回用戶信息
public function me() { return response()->json($this->guard()->user()); 或 return response()->json(JWTAuth::parseToken()->touser()); }