滑动续期、网络错误归类、API Key 激活乐观锁与生效提示
This commit is contained in:
@@ -39,10 +39,30 @@ func RequireAuth(auth *service.AuthService) gin.HandlerFunc {
|
||||
c.Set(usernameKey, username)
|
||||
c.Set(tokenVerKey, proof.Ver)
|
||||
c.Set(tokenJtiKey, proof.Jti)
|
||||
if allowsSessionRenewal(c.Request.Method) {
|
||||
maybeRenewToken(c, auth, token)
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// allowsSessionRenewal 仅允许不改变认证状态的只读请求续期。写请求可能在
|
||||
// handler 内撤销会话或递增令牌版本,预生成的续期头到响应时会已经失效。
|
||||
func allowsSessionRenewal(method string) bool {
|
||||
return method == http.MethodGet || method == http.MethodHead
|
||||
}
|
||||
|
||||
// maybeRenewToken 滑动续期:临近过期的令牌换发同会话新令牌,经响应头透出,
|
||||
// 前端读到后无感替换本地会话;未到阈值时不加头。
|
||||
func maybeRenewToken(c *gin.Context, auth *service.AuthService, token string) {
|
||||
newToken, expires, ok := auth.MaybeRenew(c.Request.Context(), token)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
c.Header("X-Renewed-Token", newToken)
|
||||
c.Header("X-Renewed-Expires-At", expires.Format(time.RFC3339))
|
||||
}
|
||||
|
||||
// tokenProofOf 取出鉴权时的令牌快照,交给敏感 service 事务复核。
|
||||
func tokenProofOf(c *gin.Context) service.TokenProof {
|
||||
v, _ := c.Get(tokenVerKey)
|
||||
|
||||
Reference in New Issue
Block a user