Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
邬吉朋
ops
Commits
52a2ed3e
"...resources/git@gitlab.ruzhoukj.com:wujipeng/relation.git" did not exist on "74bb6da3b05642ce6fb61ab8c06568c72b84424e"
Commit
52a2ed3e
authored
Jan 22, 2026
by
王蔡翾
Browse files
添加jwt
parent
0d3fe3cd
Changes
6
Hide whitespace changes
Inline
Side-by-side
pom.xml
View file @
52a2ed3e
...
...
@@ -52,6 +52,26 @@
<artifactId>
hutool-all
</artifactId>
<version>
5.8.4
</version>
</dependency>
<!-- JWT 支持,比如 jjwt -->
<dependency>
<groupId>
io.jsonwebtoken
</groupId>
<artifactId>
jjwt-api
</artifactId>
<version>
0.11.5
</version>
</dependency>
<dependency>
<groupId>
io.jsonwebtoken
</groupId>
<artifactId>
jjwt-impl
</artifactId>
<version>
0.11.5
</version>
<scope>
runtime
</scope>
</dependency>
<dependency>
<groupId>
io.jsonwebtoken
</groupId>
<artifactId>
jjwt-jackson
</artifactId>
<version>
0.11.5
</version>
<scope>
runtime
</scope>
</dependency>
<!-- 邮箱服务 -->
<dependency>
<groupId>
javax.mail
</groupId>
...
...
src/main/java/com/ruzhoukj/sms/entity/LoginEntity.java
View file @
52a2ed3e
...
...
@@ -3,6 +3,7 @@ package com.ruzhoukj.sms.entity;
import
com.baomidou.mybatisplus.annotation.IdType
;
import
com.baomidou.mybatisplus.annotation.TableId
;
import
com.baomidou.mybatisplus.annotation.TableName
;
import
io.swagger.annotations.ApiModelProperty
;
import
lombok.Data
;
import
java.math.BigInteger
;
...
...
@@ -16,5 +17,9 @@ import java.math.BigInteger;
public
class
LoginEntity
{
private
String
name
;
private
String
password
;
@ApiModelProperty
(
value
=
"访问令牌"
)
private
String
token
;
@ApiModelProperty
(
value
=
"用户ID"
)
private
String
userId
;
}
src/main/java/com/ruzhoukj/sms/entity/UserEntity.java
View file @
52a2ed3e
...
...
@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.annotation.TableField;
import
com.baomidou.mybatisplus.annotation.TableId
;
import
com.baomidou.mybatisplus.annotation.TableName
;
import
com.fasterxml.jackson.annotation.JsonFormat
;
import
io.swagger.annotations.ApiModelProperty
;
import
lombok.Data
;
import
java.util.Date
;
...
...
@@ -85,4 +86,12 @@ public class UserEntity {
@TableField
(
"dept_id"
)
private
String
deptId
;
@TableField
(
exist
=
false
)
@ApiModelProperty
(
value
=
"访问令牌"
)
private
String
token
;
@TableField
(
exist
=
false
)
@ApiModelProperty
(
value
=
"用户ID"
)
private
String
userId
;
}
src/main/java/com/ruzhoukj/sms/filter/JwtAuthFilter.java
0 → 100644
View file @
52a2ed3e
package
com.ruzhoukj.sms.filter
;
import
com.ruzhoukj.sms.util.JwtUtil
;
import
com.sun.istack.NotNull
;
import
lombok.RequiredArgsConstructor
;
import
lombok.extern.slf4j.Slf4j
;
import
lombok.var
;
import
org.springframework.core.Ordered
;
import
org.springframework.http.HttpHeaders
;
import
org.springframework.http.HttpStatus
;
import
org.springframework.stereotype.Component
;
import
org.springframework.util.AntPathMatcher
;
import
org.springframework.web.filter.OncePerRequestFilter
;
import
javax.servlet.FilterChain
;
import
javax.servlet.ServletException
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
java.io.IOException
;
import
java.util.Arrays
;
import
java.util.List
;
@Slf4j
@Component
@RequiredArgsConstructor
public
class
JwtAuthFilter
extends
OncePerRequestFilter
implements
Ordered
{
private
final
JwtUtil
jwtUtil
;
// 在类中定义
private
final
AntPathMatcher
antPathMatcher
=
new
AntPathMatcher
();
// 定义开放接口路径(支持通配符)
private
static
final
List
<
String
>
OPEN_API_PATHS
=
Arrays
.
asList
(
"/user/login"
);
@Override
protected
void
doFilterInternal
(
HttpServletRequest
request
,
@NotNull
HttpServletResponse
response
,
@NotNull
FilterChain
filterChain
)
throws
ServletException
,
IOException
{
String
path
=
request
.
getRequestURI
();
// 判断是否为公开接口(使用 AntPathMatcher 进行通配符匹配)
boolean
isPublicApi
=
OPEN_API_PATHS
.
stream
()
.
anyMatch
(
pattern
->
antPathMatcher
.
match
(
pattern
,
path
));
if
(
isPublicApi
)
{
log
.
info
(
"[JWT 过滤器] 放行公开接口: {}"
,
path
);
filterChain
.
doFilter
(
request
,
response
);
// ✅ 直接放行,不校验 token
return
;
}
// 1. 获取请求头中的 Authorization
String
authHeader
=
request
.
getHeader
(
HttpHeaders
.
AUTHORIZATION
);
// 2. 校验是否携带了 Bearer Token
if
(
authHeader
==
null
||
!
authHeader
.
startsWith
(
"Bearer "
))
{
log
.
warn
(
"[JWT 校验失败] 缺少或格式错误的 Authorization Header"
);
sendUnauthorized
(
response
,
"未提供有效的身份凭证"
);
return
;
}
// 3. 提取 Token(去掉 "Bearer " 前缀)
String
token
=
authHeader
.
substring
(
7
).
trim
();
try
{
// 4. 解析 & 校验 JWT Token
var
claims
=
jwtUtil
.
parseToken
(
token
);
// 5. 从 Token 中提取用户身份信息(根据你生成时的 claims 名称)
String
userName
=
claims
.
get
(
"name"
,
String
.
class
);
// 你生成时放入的 key
if
(
userName
==
null
)
{
log
.
warn
(
"[JWT 校验失败] Token 中缺少 name"
);
sendUnauthorized
(
response
,
"无效的用户身份信息"
);
return
;
}
log
.
info
(
"[JWT 校验成功] , 用户名: {}"
,
userName
);
// 6. 透传用户身份到下游服务(添加请求头)
// 注意:在普通Servlet环境中,我们设置请求属性而不是修改请求头
request
.
setAttribute
(
"X-Username"
,
userName
);
// 如果需要设置请求头供后续控制器使用,可以考虑使用ThreadLocal或其他方式
// 或者在某些框架中可以使用自定义的RequestWrapper
// 7. 继续过滤器链,下游服务可以获取用户信息
filterChain
.
doFilter
(
request
,
response
);
}
catch
(
RuntimeException
e
)
{
log
.
warn
(
"[JWT 校验失败] Token 无效: {}"
,
e
.
getMessage
());
sendUnauthorized
(
response
,
"无效的 Token: "
+
e
.
getMessage
());
}
}
/**
* 发送401未授权响应
*/
private
void
sendUnauthorized
(
HttpServletResponse
response
,
String
message
)
throws
IOException
{
response
.
setStatus
(
HttpStatus
.
UNAUTHORIZED
.
value
());
response
.
setContentType
(
"application/json;charset=UTF-8"
);
// 返回JSON格式的错误信息
String
errorResponse
=
String
.
format
(
"{\"code\": %d, \"message\": \"%s\"}"
,
HttpStatus
.
UNAUTHORIZED
.
value
(),
message
);
response
.
getWriter
().
write
(
errorResponse
);
}
@Override
public
int
getOrder
()
{
return
Ordered
.
HIGHEST_PRECEDENCE
;
// 高优先级,最先执行
}
}
\ No newline at end of file
src/main/java/com/ruzhoukj/sms/service/impl/LoginServiceImpl.java
View file @
52a2ed3e
...
...
@@ -5,22 +5,27 @@ import com.ruzhoukj.sms.dao.UserDao;
import
com.ruzhoukj.sms.entity.LoginEntity
;
import
com.ruzhoukj.sms.entity.UserEntity
;
import
com.ruzhoukj.sms.service.LoginService
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
com.ruzhoukj.sms.util.JwtUtil
;
import
org.springframework.stereotype.Service
;
import
javax.annotation.Resource
;
@Service
public
class
LoginServiceImpl
extends
ServiceImpl
<
UserDao
,
UserEntity
>
implements
LoginService
{
@Resource
private
JwtUtil
jwtUtil
;
@Override
public
UserEntity
login
(
LoginEntity
login
)
{
// 根据用户名查询用户信息
UserEntity
user
=
baseMapper
.
getUserByUsernameAndPassword
(
login
.
getName
(),
login
.
getPassword
());
if
(
user
==
null
)
{
throw
new
RuntimeException
(
"用户名或者密码错误"
);
}
// 4. 生成 JWT Token
String
token
=
jwtUtil
.
generateToken
(
String
.
valueOf
(
user
.
getId
()),
user
.
getName
());
// 判断密码是否匹配
if
(
user
!=
null
)
{
return
user
;
}
else
{
return
null
;
}
user
.
setToken
(
token
);
return
user
;
}
}
\ No newline at end of file
src/main/java/com/ruzhoukj/sms/util/JwtUtil.java
0 → 100644
View file @
52a2ed3e
package
com.ruzhoukj.sms.util
;
import
io.jsonwebtoken.Claims
;
import
io.jsonwebtoken.Jwts
;
import
io.jsonwebtoken.SignatureAlgorithm
;
import
io.jsonwebtoken.security.Keys
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.stereotype.Component
;
import
javax.crypto.SecretKey
;
import
java.util.Date
;
import
java.util.HashMap
;
import
java.util.Map
;
@Component
public
class
JwtUtil
{
@Value
(
"${jwt.secret:7xK9p2Rz4nQvTxoLmYwEfD1cAq6sNjBvXyZtH3uFcW0iJm5LoRgUdSeP2iKq}"
)
// 请使用安全的密钥,至少32字符!
private
String
secret
;
@Value
(
"${jwt.expiration:28800}"
)
// Token有效期(秒),比如 8小时
private
Long
expiration
;
// 生成 JWT Token
public
String
generateToken
(
String
userId
,
String
name
)
{
Map
<
String
,
Object
>
claims
=
new
HashMap
<>();
claims
.
put
(
"userId"
,
userId
);
claims
.
put
(
"name"
,
name
);
Date
now
=
new
Date
();
Date
expiryDate
=
new
Date
(
now
.
getTime
()
+
expiration
*
1000L
);
SecretKey
key
=
Keys
.
hmacShaKeyFor
(
secret
.
getBytes
());
return
Jwts
.
builder
()
.
setClaims
(
claims
)
.
setSubject
(
userId
)
// 主题,通常放用户ID
.
setIssuedAt
(
now
)
.
setExpiration
(
expiryDate
)
.
signWith
(
key
,
SignatureAlgorithm
.
HS256
)
.
compact
();
}
// 从 Token 中解析数据(比如用于网关校验)
public
Claims
parseToken
(
String
token
)
{
SecretKey
key
=
Keys
.
hmacShaKeyFor
(
secret
.
getBytes
());
return
Jwts
.
parserBuilder
()
.
setSigningKey
(
key
)
.
build
()
.
parseClaimsJws
(
token
)
.
getBody
();
}
/**
* 解析 Token 并直接返回 userName
* @param token JWT Token(可以是原始token或带"Bearer "前缀的token)
* @return 用户名
* @throws RuntimeException 当 Token 无效或解析失败时抛出
*/
public
String
getUserNameFromToken
(
String
token
)
{
try
{
// 预处理token,去除可能的空格和Bearer前缀
if
(
token
!=
null
)
{
token
=
token
.
trim
();
if
(
token
.
startsWith
(
"Bearer "
))
{
token
=
token
.
substring
(
7
).
trim
();
}
}
// 检查token是否为空
if
(
token
==
null
||
token
.
isEmpty
())
{
throw
new
RuntimeException
(
"Token 不能为空"
);
}
// 修改后代码:
SecretKey
key
=
Keys
.
hmacShaKeyFor
(
secret
.
getBytes
());
Claims
claims
=
Jwts
.
parserBuilder
()
.
setSigningKey
(
key
)
.
build
()
.
parseClaimsJws
(
token
)
.
getBody
();
// 优先从subject获取,如果没有则从userName字段获取
String
name
=
claims
.
get
(
"name"
,
String
.
class
);
if
(
name
==
null
||
name
.
isEmpty
())
{
throw
new
RuntimeException
(
"Token 中缺少用户信息"
);
}
return
name
;
}
catch
(
io
.
jsonwebtoken
.
ExpiredJwtException
e
)
{
throw
new
RuntimeException
(
"Token 已过期"
);
}
catch
(
io
.
jsonwebtoken
.
MalformedJwtException
e
)
{
throw
new
RuntimeException
(
"Token 格式错误"
);
}
catch
(
io
.
jsonwebtoken
.
UnsupportedJwtException
e
)
{
throw
new
RuntimeException
(
"不支持的 Token 格式"
);
}
catch
(
IllegalArgumentException
e
)
{
throw
new
RuntimeException
(
"Token 参数异常"
);
}
catch
(
Exception
e
)
{
throw
new
RuntimeException
(
"Token 解析失败: "
+
e
.
getMessage
());
}
}
/**
* 安全版本的解析方法,返回 null 而不是抛出异常
* @param token JWT Token
* @return 用户名,解析失败返回 null
*/
public
String
getUserNameFromTokenSafe
(
String
token
)
{
try
{
return
getUserNameFromToken
(
token
);
}
catch
(
Exception
e
)
{
// 记录日志但不抛出异常
System
.
err
.
println
(
"解析 Token 失败: "
+
e
.
getMessage
());
return
null
;
}
}
/**
* 从 Authorization Header 中提取并解析 userName
* @param authHeader Authorization Header 值(格式:Bearer <token>)
* @return 用户名
* @throws RuntimeException 当 Header 格式错误或 Token 解析失败时抛出
*/
public
String
getUserNameFromAuthHeader
(
String
authHeader
)
{
if
(
authHeader
==
null
||
!
authHeader
.
startsWith
(
"Bearer "
))
{
throw
new
RuntimeException
(
"Authorization Header 格式错误,应为: Bearer <token>"
);
}
String
token
=
authHeader
.
substring
(
7
).
trim
();
return
getUserNameFromToken
(
token
);
}
/**
* 验证 Token 是否有效且包含 userName
* @param token JWT Token
* @return 是否有效
*/
public
boolean
validateTokenAndHasUserName
(
String
token
)
{
try
{
Claims
claims
=
parseToken
(
token
);
String
userName
=
claims
.
get
(
"name"
,
String
.
class
);
return
userName
!=
null
&&
!
userName
.
trim
().
isEmpty
();
}
catch
(
Exception
e
)
{
return
false
;
}
}
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
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 comment