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()); }