Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
usedCarAuction
/
aus
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit c40a3be3
authored
Apr 01, 2026
by
章家宝
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
feat: 用户登出接口将token加入到黑名单中
1 parent
352e6c74
Hide whitespace changes
Inline
Side-by-side
Showing
3 changed files
with
142 additions
and
26 deletions
aus-inspector/src/main/java/com/glsx/usedcar/controller/AuthController.java
aus-inspector/src/main/java/com/glsx/usedcar/interceptor/LoginInterceptor.java
aus-inspector/src/main/java/com/glsx/usedcar/token/JwtProvider.java
aus-inspector/src/main/java/com/glsx/usedcar/controller/AuthController.java
View file @
c40a3be
...
...
@@ -13,13 +13,17 @@ import com.glsx.usedcar.util.*;
import
io.swagger.v3.oas.annotations.Operation
;
import
io.swagger.v3.oas.annotations.Parameter
;
import
io.swagger.v3.oas.annotations.tags.Tag
;
import
jakarta.servlet.http.HttpServletRequest
;
import
jakarta.validation.Valid
;
import
lombok.RequiredArgsConstructor
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.web.bind.annotation.*
;
import
org.summerframework.core.enums.ErrorCodeEnum
;
import
org.summerframework.core.exception.BusinessCodeException
;
import
java.time.LocalDateTime
;
import
java.util.Date
;
/**
* 认证控制器:负责登录、验证码发送、退出登录等认证相关接口
...
...
@@ -37,6 +41,10 @@ public class AuthController {
private
final
EnvProfileUtils
envProfileUtils
;
@Value
(
"${sms.code-expire:300}"
)
private
int
codeExpire
;
@Value
(
"${jwt.header:Authorization}"
)
private
String
jwtHeader
;
@Value
(
"${jwt.token-prefix:Bearer}"
)
private
String
tokenPrefix
;
/**
* 发送短信验证码(带频率防刷控制)
...
...
@@ -106,21 +114,32 @@ public class AuthController {
return
BaseResp
.
success
(
resp
);
}
/**
* 退出登录接口(需携带有效登录Token)
* 注:当前仅返回退出成功,实际生产环境可补充Token黑名单/失效逻辑
*
* @return 退出结果:success=true表示退出成功
*/
@Operation
(
summary
=
"退出登录"
,
description
=
"检测员退出登录(需携带有效JWT Token),当前仅返回成功状态,可扩展Token失效逻辑"
)
@Operation
(
summary
=
"退出登录"
,
description
=
"检测员退出登录,Token加入黑名单失效"
)
@PostMapping
(
"/logout"
)
@RequireLogin
public
BaseResp
<
Boolean
>
logout
()
{
public
BaseResp
<
Boolean
>
logout
(
HttpServletRequest
request
)
{
String
phone
=
InspectorContext
.
getPhone
();
log
.
info
(
"检测员{}执行退出登录操作"
,
phone
);
// 1. 从请求头获取Token
String
authHeader
=
request
.
getHeader
(
jwtHeader
);
if
(
authHeader
==
null
||
!
authHeader
.
startsWith
(
tokenPrefix
))
{
log
.
warn
(
"用户{}登出失败:Token格式错误"
,
phone
);
throw
new
BusinessCodeException
(
ErrorCodeEnum
.
COMMON_ERROR
,
"登出失败,无效Token"
);
}
String
token
=
authHeader
.
substring
(
tokenPrefix
.
length
()).
trim
();
// 2. 获取Token剩余有效期
Date
expireTime
=
jwtProvider
.
getTokenExpireTime
(
token
);
if
(
expireTime
==
null
)
{
log
.
warn
(
"用户{}登出失败:Token已过期"
,
phone
);
return
BaseResp
.
success
(
true
);
}
long
remainSeconds
=
(
expireTime
.
getTime
()
-
System
.
currentTimeMillis
())
/
1000
;
// 3. 将Token加入黑名单(设置相同过期时间)
jwtProvider
.
addTokenToBlacklist
(
token
,
remainSeconds
);
log
.
info
(
"用户{}登出成功,Token已加入黑名单"
,
phone
);
return
BaseResp
.
success
(
true
);
}
...
...
aus-inspector/src/main/java/com/glsx/usedcar/interceptor/LoginInterceptor.java
View file @
c40a3be
...
...
@@ -11,7 +11,6 @@ import jakarta.servlet.http.HttpServletRequest;
import
jakarta.servlet.http.HttpServletResponse
;
import
lombok.RequiredArgsConstructor
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.stereotype.Component
;
...
...
@@ -22,7 +21,7 @@ import org.summerframework.core.enums.ErrorCodeEnum;
import
java.io.PrintWriter
;
/**
* 登录认证拦截器
:处理@RequireLogin注解,校验Token
* 登录认证拦截器
(增加黑名单校验)
*/
@Slf4j
@Component
...
...
@@ -50,7 +49,6 @@ public class LoginInterceptor implements HandlerInterceptor {
return
true
;
}
// 有@RequireLogin注解,校验Token
String
authHeader
=
request
.
getHeader
(
jwtHeader
);
if
(
authHeader
==
null
||
authHeader
.
trim
().
isEmpty
()
||
!
authHeader
.
startsWith
(
tokenPrefix
))
{
returnErrorResponse
(
response
,
"未登录或Token格式错误"
);
...
...
@@ -67,6 +65,13 @@ public class LoginInterceptor implements HandlerInterceptor {
return
false
;
}
// ========== 新增:黑名单校验 ==========
if
(
jwtProvider
.
isTokenInBlacklist
(
token
))
{
returnErrorResponse
(
response
,
"Token已失效(已登出)"
);
return
false
;
}
// 原有用户校验逻辑(不变)
if
(
phone
==
null
||
phone
.
trim
().
isEmpty
())
{
returnErrorResponse
(
response
,
"Token无效或已过期"
);
return
false
;
...
...
aus-inspector/src/main/java/com/glsx/usedcar/token/JwtProvider.java
View file @
c40a3be
package
com
.
glsx
.
usedcar
.
token
;
import
com.auth0.jwt.JWT
;
import
com.auth0.jwt.exceptions.JWTVerificationException
;
import
com.auth0.jwt.exceptions.TokenExpiredException
;
import
com.auth0.jwt.interfaces.DecodedJWT
;
import
com.glsx.usedcar.util.RedisCacheUtil
;
import
lombok.RequiredArgsConstructor
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.beans.factory.annotation.Autowired
;
...
...
@@ -11,7 +13,8 @@ import org.summerframework.web.auth.AbstractJwtProvider;
import
java.time.LocalDateTime
;
import
java.util.Date
;
import
java.util.UUID
;
import
java.util.concurrent.TimeUnit
;
/**
* JWT认证服务
...
...
@@ -20,21 +23,23 @@ import java.util.Date;
@Component
@RequiredArgsConstructor
(
onConstructor
=
@__
(
@Autowired
))
public
class
JwtProvider
extends
AbstractJwtProvider
{
/**
* 生成token
*
* @return token
*/
private
final
RedisCacheUtil
redisCacheUtil
;
private
static
final
String
INSPECTOR_LOGIN_UID
=
"uid"
;
private
static
final
String
JWT_BLACKLIST_UID_PREFIX
=
"jwt:blacklist:uid:"
;
public
String
generateUser
(
String
phone
,
Date
expireTime
)
{
try
{
String
uid
=
UUID
.
randomUUID
().
toString
().
replace
(
"-"
,
""
);
return
JWT
.
create
()
.
withIssuer
(
jwtProperties
.
getIssuer
())
.
withIssuedAt
(
new
Date
())
.
withExpiresAt
(
expireTime
)
.
withClaim
(
INSPECTOR_LOGIN_UID
,
uid
)
.
withJWTId
(
phone
)
.
withSubject
(
phone
)
.
sign
(
algorithm
);
}
catch
(
IllegalArgumentException
|
TokenExpiredException
e
)
{
log
.
error
(
"生成用户Token失败,phone:{}"
,
phone
,
e
);
return
null
;
}
}
...
...
@@ -44,12 +49,11 @@ public class JwtProvider extends AbstractJwtProvider {
return
now
.
plusSeconds
(
jwtProperties
.
getExpiration
());
}
/**
* 解析token
* 解析token
(校验签名+有效期,返回手机号)
*
* @param token token
* @return phone
* @return phone
解析成功返回手机号,失败返回null
*/
public
String
verify
(
String
token
)
{
if
(
token
==
null
)
{
...
...
@@ -58,10 +62,98 @@ public class JwtProvider extends AbstractJwtProvider {
try
{
DecodedJWT
jwt
=
verifier
.
verify
(
token
);
return
jwt
.
getSubject
();
}
catch
(
Exception
e
)
{
}
catch
(
JWTVerificationException
e
)
{
// 精准捕获JWT校验异常
log
.
error
(
"Token校验失败:{}"
,
token
,
e
);
return
null
;
}
}
/**
* 获取Token的过期时间(即使Token过期也能解析)
*
* @param token token
* @return 过期时间,解析失败返回null
*/
public
Date
getTokenExpireTime
(
String
token
)
{
if
(
token
==
null
)
{
return
null
;
}
try
{
// 先尝试verify(未过期的Token),失败则直接decode(已过期的Token)
DecodedJWT
jwt
;
try
{
jwt
=
verifier
.
verify
(
token
);
}
catch
(
TokenExpiredException
e
)
{
// Token过期但仍可解析expiresAt
jwt
=
JWT
.
decode
(
token
);
}
return
jwt
.
getExpiresAt
();
}
catch
(
Exception
e
)
{
// 精准捕获JWT相关异常
log
.
error
(
"解析Token过期时间失败, token:{}"
,
token
,
e
);
return
null
;
}
}
/**
* 从Token中解析出uid(生成Token时存入的claim)
* 支持解析已过期的Token(仅解析,不校验签名/有效期)
*
* @param token token
* @return uid 解析成功返回uid,失败返回null
*/
public
String
getUidFromToken
(
String
token
)
{
if
(
token
==
null
)
{
return
null
;
}
try
{
DecodedJWT
jwt
;
// 优先校验(未过期Token),失败则直接解码(已过期Token)
try
{
jwt
=
verifier
.
verify
(
token
);
}
catch
(
JWTVerificationException
e
)
{
jwt
=
JWT
.
decode
(
token
);
}
return
jwt
.
getClaim
(
INSPECTOR_LOGIN_UID
).
asString
();
}
catch
(
Exception
e
)
{
// 兜底捕获解码异常(如Token格式错误)
log
.
error
(
"解析Token中的uid失败, token:{}"
,
token
,
e
);
return
null
;
}
}
/**
* 校验uid是否在黑名单(已登出)
*
* @param token token
* @return true=在黑名单,false=不在/Token无效
*/
public
boolean
isTokenInBlacklist
(
String
token
)
{
String
uid
=
getUidFromToken
(
token
);
// uid为null时直接返回false,避免检查无效Key
if
(
uid
==
null
)
{
return
false
;
}
return
redisCacheUtil
.
existsKey
(
JWT_BLACKLIST_UID_PREFIX
+
uid
);
}
}
/**
* 将uid加入黑名单(关联Token过期时间)
*
* @param token token
* @param expireSeconds 过期秒数(需>0)
*/
public
void
addTokenToBlacklist
(
String
token
,
long
expireSeconds
)
{
// 多层校验:避免无效参数
if
(
token
==
null
||
expireSeconds
<=
0
)
{
log
.
warn
(
"加入黑名单失败:Token为空或过期时间无效,token:{}, expireSeconds:{}"
,
token
,
expireSeconds
);
return
;
}
String
uid
=
getUidFromToken
(
token
);
if
(
uid
==
null
)
{
log
.
warn
(
"加入黑名单失败:解析Token的uid失败,token:{}"
,
token
);
return
;
}
String
blacklistKey
=
JWT_BLACKLIST_UID_PREFIX
+
uid
;
redisCacheUtil
.
setCacheWithExpire
(
blacklistKey
,
"1"
,
expireSeconds
,
TimeUnit
.
SECONDS
);
log
.
info
(
"UID已加入黑名单,key:{}, 过期时间:{}秒"
,
blacklistKey
,
expireSeconds
);
}
}
\ No newline at end of file
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment