https://learnku.com/articles/10885/full-use-of-jwt
composer.json的require中加入下面的包,composer install
"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
先引入下面内容:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
config/auth.php
api->driver=>'token',修改为'jwt'
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
在exceptopns中的Handler 的render方法中加入下面代码全局定义返回错误
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);
将用户模型关联上
1. 通过token获取用户
JWTAuth::toUser( $tokenStr );
2. 通过用户获取token
在需要的模型里面添加
在需要的模型里面添加
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) 生成token
一般是不能用于登陆的(如果登陆的用户生成的token,则可以用于登陆)
// 创建负载
$customClaims = ['foo' => 'bar', 'baz' => 'bob'];
$payload = JWTFactory::make($customClaims);
$token = JWTAuth::encode($payload);
登录
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());
}