JWT 刷新token详解

laravel中使用jwt生成token,以下是代码示例

use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends Controller
{
    // 登录接口
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (!$token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
    }

    // 返回 Token 响应
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60, // access_token 过期时间
            'refresh_token' => auth()->claims(['type' => 'refresh'])->setTTL(43200)->tokenById(auth()->id()) // 30 天
        ]);
    }

    // 刷新 Token 接口
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    // 登出接口
    public function logout()
    {
        auth()->logout();
        return response()->json(['message' => '成功退出登录']);
    }

    // 获取用户信息
    public function profile()
    {
        return response()->json(auth()->user());
    }
}

在config/jwt配置:

'ttl' => 60, // access_token 有效期 (分钟)
'refresh_ttl' => 43200, // refresh_token 有效期 (分钟)
 

说明:token的有效期是ttl时长(包括刷新的token有效时长), 可刷新token的时间范围是refresh_ttl时长

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值