🎓博主介绍:Java、Python、js全栈开发 “多面手”,精通多种编程语言和技术,痴迷于人工智能领域。秉持着对技术的热爱与执着,持续探索创新,愿在此分享交流和学习,与大家共进步。
📖DeepSeek-行业融合之万象视界(附实战案例详解100+)
📖全栈开发环境搭建运行攻略:多语言一站式指南(环境搭建+运行+调试+发布+保姆级详解)
👉感兴趣的可以先收藏起来,希望帮助更多的人
SpringBoot安全框架全攻略:整合SpringSecurity与JWT认证
一、引言
在当今的Web应用开发中,安全性是至关重要的一环。Spring Boot作为一款流行的Java开发框架,为开发者提供了便捷的开发体验。而Spring Security则是Spring生态系统中用于实现身份验证和授权的强大框架。JSON Web Token(JWT)是一种轻量级的开放标准(RFC 7519),用于在网络应用之间安全地传输声明。本文将详细介绍如何在Spring Boot项目中整合Spring Security和JWT认证,为你的应用提供安全可靠的身份验证机制。
二、环境准备
2.1 开发工具
- 集成开发环境(IDE):推荐使用IntelliJ IDEA或Eclipse。
- 构建工具:Maven或Gradle,本文以Maven为例。
2.2 依赖配置
在pom.xml
文件中添加以下依赖:
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- jjwt API -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<!-- jjwt implementation -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<!-- jjwt Jackson -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
</dependencies>
三、JWT基础
3.1 JWT结构
JWT由三部分组成,用点(.)分隔:
- Header(头部):包含令牌的类型(通常是JWT)和使用的签名算法,如HMAC SHA256或RSA。
- Payload(负载):包含声明(Claims),声明是关于实体(通常是用户)和其他数据的声明。
- Signature(签名):用于验证消息在传递过程中没有被更改,并且在使用私钥签名的情况下,还可以验证JWT的发送者的身份。
3.2 JWT工作流程
- 用户登录:用户向服务器发送用户名和密码进行登录。
- 服务器验证:服务器验证用户的凭证,如果验证通过,生成一个JWT。
- 返回JWT:服务器将生成的JWT返回给客户端。
- 客户端存储:客户端将JWT存储在本地,如LocalStorage或Cookie中。
- 后续请求:客户端在后续的请求中,将JWT放在请求头中发送给服务器。
- 服务器验证:服务器验证JWT的有效性,如果有效,则处理请求并返回响应。
四、Spring Security基础
4.1 Spring Security架构
Spring Security的核心是过滤器链,它会拦截所有的HTTP请求,并根据配置的规则进行身份验证和授权。主要组件包括:
- AuthenticationManager:负责处理身份验证请求。
- UserDetailsService:用于加载用户信息。
- PasswordEncoder:用于对密码进行加密和解密。
4.2 Spring Security配置
创建一个配置类,继承WebSecurityConfigurerAdapter
,并进行相关配置:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
}
五、整合Spring Security与JWT认证
5.1 创建JWT工具类
创建一个JWT工具类,用于生成和验证JWT:
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtUtil {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return doGenerateToken(claims, userDetails.getUsername());
}
private String doGenerateToken(Map<String, Object> claims, String subject) {
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
public String extractUsername(String token) {
return extractClaims(token).getSubject();
}
private Boolean isTokenExpired(String token) {
final Date expiration = extractClaims(token).getExpiration();
return expiration.before(new Date());
}
private Claims extractClaims(String token) {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}
}
5.2 创建JWT认证过滤器
创建一个JWT认证过滤器,用于拦截请求并验证JWT:
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
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;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String requestTokenHeader = request.getHeader("Authorization");
String username = null;
String jwtToken = null;
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
username = jwtUtil.extractUsername(jwtToken);
} catch (IllegalArgumentException e) {
System.out.println("Unable to get JWT Token");
} catch (ExpiredJwtException e) {
System.out.println("JWT Token has expired");
}
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtUtil.validateToken(jwtToken, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
chain.doFilter(request, response);
}
}
5.3 更新Spring Security配置
在SecurityConfig
类中添加JWT认证过滤器:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationFilter jwtAuthenticationFilter;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
}
5.4 创建认证接口
创建一个认证接口,用于用户登录并返回JWT:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtUtil jwtUtil;
@PostMapping("/login")
public ResponseEntity<?> createAuthenticationToken(@RequestBody Map<String, String> authenticationRequest) throws Exception {
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(authenticationRequest.get("username"), authenticationRequest.get("password"))
);
} catch (BadCredentialsException e) {
throw new Exception("Incorrect username or password", e);
}
final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.get("username"));
final String jwt = jwtUtil.generateToken(userDetails);
Map<String, String> response = new HashMap<>();
response.put("token", jwt);
return ResponseEntity.ok(response);
}
}
六、测试与验证
6.1 启动项目
使用IDE或Maven命令mvn spring-boot:run
启动Spring Boot项目。
6.2 发送登录请求
使用Postman或其他工具发送POST请求到/api/auth/login
,请求体如下:
{
"username": "testuser",
"password": "testpassword"
}
如果用户名和密码正确,服务器将返回一个JWT。示例响应如下:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0dXNlciIsImV4cCI6MTY5MjQyMzYwMCwiaWF0IjoxNjkyNDIwMDAwfQ.Sz6y7m8n9o0p1q2r3s4t5u6v7w8x9y0z1A2B3C4D5E6F7G8H9I0J1K2L3M4N5O6P7Q8R9S0T1U2V3W4X5Y6Z7a8b9c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4P5Q6R7S8T9U0V1W2X3Y4Z5a6b7c8d9e0f1g2h3i4j5k6l7m8n9o0p1q2r3s4t5u6v7w8x9y0z1A2B3C4D5E6F7G8H9I0J1K2L3M4N5O6P7Q8R9S0T1U2V3W4X5Y6Z7a8b9c0d1e2f3g4h5i6j7k8l9m0n1o2p3q4r5s6t7u8v9w0x1y2z3A4B5C6D7E8F9G0H1I2J3K4L5M6N7O8P9Q0R1S2T3U4V5W6X7Y8Z9a0b1c2d3e4f5g6h7i8j9k0l1m2n3o4p5q6r7s8t9u0v1w2x3y4z5A6B7C8D9E0F1G2H3I4J5K6L7M8N9O0P1Q2R3S4T5U6V7W8X9Y0Z1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s0t1u2v3w4x5y6z7A8B9C0D1E2F3G4H5I6J7K8L9M0N1O2P3Q4R5S6T7U8V9W0X1Y2Z3a4b5c6d7e8f9g0h1i2j3k4l5m6n7o8p9q0r1s2t3u4v5w6x7y8z9A0B1C2D3E4F5G6H7I8J9K0L1M2N3O4P5Q6R7S8T9U0V1W2X3Y4Z5"
}
这个JWT包含了用户的身份信息,后续的受保护请求需要携带这个JWT来进行身份验证。
6.3 发送受保护的请求
在后续的请求中,将JWT放在请求头的Authorization
字段中,格式为Bearer <JWT>
。例如,使用Postman发送一个GET请求到受保护的接口/api/protected
,在请求头中添加如下信息:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0dXNlciIsImV4cCI6MTY5MjQyMzYwMCwiaWF0IjoxNjkyNDIwMDAwfQ.Sz6y7m8n9o0p1q2r3s4t5u6v7w8x9y0z1A2B3C4D5E6F7G8H9I0J1K2L3M4N5O6P7Q8R9S0T1U2V3W4X5Y6Z7a8b9c0d1e2f3g4h5i6j7k8l9m0n1o2p3q4r5s6t7u8v9w0x1y2z3A4B5C6D7E8F9G0H1I2J3K4L5M6N7O8P9Q0R1S2T3U4V5W6X7Y8Z9a0b1c2d3e4f5g6h7i8j9k0l1m2n3o4p5q6r7s8t9u0v1w2x3y4z5A6B7C8D9E0F1G2H3I4J5K6L7M8N9O0P1Q2R3S4T5U6V7W8X9Y0Z1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s0t1u2v3w4x5y6z7A8B9C0D1E2F3G4H5I6J7K8L9M0N1O2P3Q4R5S6T7U8V9W0X1Y2Z3a4b5c6d7e8f9g0h1i2j3k4l5m6n7o8p9q0r1s2t3u4v5w6x7y8z9A0B1C2D3E4F5G6H7I8J9K0L1M2N3O4P5Q6R7S8T9U0V1W2X3Y4Z5
服务器收到请求后,JwtAuthenticationFilter
会拦截该请求,从请求头中提取JWT,并进行验证:
- 首先,验证JWT的签名是否有效,确保JWT在传输过程中没有被篡改。
- 然后,检查JWT是否过期。
- 如果签名有效且未过期,从JWT中提取用户名,并根据用户名加载用户信息。
- 最后,将用户信息设置到Spring Security的上下文(
SecurityContextHolder
)中,表示用户已认证。
如果验证通过,服务器将正常处理该请求并返回响应;如果验证失败,服务器将返回相应的错误信息,如401 Unauthorized。
6.4 处理JWT过期和刷新
6.4.1 JWT过期处理
当JWT过期时,JwtUtil
类中的isTokenExpired
方法会返回true
。在JwtAuthenticationFilter
中,当捕获到ExpiredJwtException
异常时,会输出日志信息“JWT Token has expired”,并继续执行后续过滤器链,但不会将用户信息设置到安全上下文中,因此该请求会被视为未认证请求,服务器会返回401 Unauthorized。
6.4.2 JWT刷新机制
为了避免用户频繁登录,可以实现JWT刷新机制。一种常见的做法是在用户登录时,除了返回JWT,还返回一个刷新令牌(Refresh Token)。当JWT过期时,客户端可以使用刷新令牌向服务器发送刷新请求,服务器验证刷新令牌的有效性,如果有效,则生成一个新的JWT返回给客户端。
以下是实现刷新机制的步骤:
- 修改登录接口:在登录接口返回JWT的同时,返回一个刷新令牌。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private JwtUtil jwtUtil;
@PostMapping("/login")
public ResponseEntity<?> createAuthenticationToken(@RequestBody Map<String, String> authenticationRequest) throws Exception {
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(authenticationRequest.get("username"), authenticationRequest.get("password"))
);
} catch (BadCredentialsException e) {
throw new Exception("Incorrect username or password", e);
}
final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.get("username"));
final String jwt = jwtUtil.generateToken(userDetails);
final String refreshToken = jwtUtil.generateRefreshToken(userDetails);
Map<String, String> response = new HashMap<>();
response.put("token", jwt);
response.put("refreshToken", refreshToken);
return ResponseEntity.ok(response);
}
}
- 添加刷新接口:创建一个刷新接口,用于处理刷新请求。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/auth")
public class RefreshTokenController {
@Autowired
private JwtUtil jwtUtil;
@PostMapping("/refresh")
public ResponseEntity<?> refreshToken(@RequestBody Map<String, String> refreshRequest) {
String refreshToken = refreshRequest.get("refreshToken");
if (jwtUtil.validateRefreshToken(refreshToken)) {
String username = jwtUtil.extractUsernameFromRefreshToken(refreshToken);
String newToken = jwtUtil.generateTokenByUsername(username);
Map<String, String> response = new HashMap<>();
response.put("token", newToken);
return ResponseEntity.ok(response);
}
return ResponseEntity.status(401).body("Invalid refresh token");
}
}
- 修改JwtUtil类:添加生成刷新令牌、验证刷新令牌和从刷新令牌中提取用户名的方法。
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtUtil {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
@Value("${jwt.refresh.expiration}")
private Long refreshExpiration;
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return doGenerateToken(claims, userDetails.getUsername());
}
public String generateRefreshToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return doGenerateRefreshToken(claims, userDetails.getUsername());
}
private String doGenerateToken(Map<String, Object> claims, String subject) {
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
private String doGenerateRefreshToken(Map<String, Object> claims, String subject) {
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + refreshExpiration * 1000))
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
public Boolean validateRefreshToken(String refreshToken) {
return !isTokenExpired(refreshToken);
}
public String extractUsername(String token) {
return extractClaims(token).getSubject();
}
public String extractUsernameFromRefreshToken(String refreshToken) {
return extractClaims(refreshToken).getSubject();
}
public String generateTokenByUsername(String username) {
Map<String, Object> claims = new HashMap<>();
return doGenerateToken(claims, username);
}
private Boolean isTokenExpired(String token) {
final Date expiration = extractClaims(token).getExp### 6.4.2 JWT刷新机制
#### 6.4.2.1 刷新令牌的存储与管理
在实际应用中,刷新令牌需要妥善存储和管理。可以将刷新令牌存储在数据库中,并关联到对应的用户。在生成刷新令牌时,记录其生成时间、过期时间等信息。例如,创建一个`RefreshToken`实体类:
```java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;
@Entity
public class RefreshToken {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String token;
private String username;
private Date issuedAt;
private Date expiresAt;
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getIssuedAt() {
return issuedAt;
}
public void setIssuedAt(Date issuedAt) {
this.issuedAt = issuedAt;
}
public Date getExpiresAt() {
return expiresAt;
}
public void setExpiresAt(Date expiresAt) {
this.expiresAt = expiresAt;
}
}
同时,创建一个RefreshTokenRepository
接口来操作数据库:
import org.springframework.data.jpa.repository.JpaRepository;
public interface RefreshTokenRepository extends JpaRepository<RefreshToken, Long> {
RefreshToken findByToken(String token);
}
6.4.2.2 刷新流程的优化
在刷新接口中,除了验证刷新令牌的有效性,还需要从数据库中检查该刷新令牌是否存在且未被使用。以下是优化后的刷新接口代码:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/auth")
public class RefreshTokenController {
@Autowired
private JwtUtil jwtUtil;
@Autowired
private RefreshTokenRepository refreshTokenRepository;
@PostMapping("/refresh")
public ResponseEntity<?> refreshToken(@RequestBody Map<String, String> refreshRequest) {
String refreshToken = refreshRequest.get("refreshToken");
RefreshToken storedRefreshToken = refreshTokenRepository.findByToken(refreshToken);
if (storedRefreshToken != null && jwtUtil.validateRefreshToken(refreshToken)) {
String username = jwtUtil.extractUsernameFromRefreshToken(refreshToken);
String newToken = jwtUtil.generateTokenByUsername(username);
Map<String, String> response = new HashMap<>();
response.put("token", newToken);
return ResponseEntity.ok(response);
}
return ResponseEntity.status(401).body("Invalid refresh token");
}
}
6.4.2.3 刷新令牌的安全性考虑
为了增强刷新令牌的安全性,可以采取以下措施:
- 设置合理的过期时间:刷新令牌的过期时间应该比JWT的过期时间长,但也不能过长,以免被攻击者利用。
- 使用HTTPS:在传输刷新令牌时,必须使用HTTPS协议,防止令牌在传输过程中被截获。
- 及时销毁旧的刷新令牌:当使用刷新令牌生成新的JWT后,应该及时销毁旧的刷新令牌,防止重复使用。
6.5 错误处理与异常定制
6.5.1 自定义异常处理类
在Spring Boot中,可以创建一个全局异常处理类来统一处理各种异常。例如:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BadCredentialsException.class)
public ResponseEntity<String> handleBadCredentialsException(BadCredentialsException ex) {
return new ResponseEntity<>("Incorrect username or password", HttpStatus.UNAUTHORIZED);
}
@ExceptionHandler(ExpiredJwtException.class)
public ResponseEntity<String> handleExpiredJwtException(ExpiredJwtException ex) {
return new ResponseEntity<>("JWT Token has expired", HttpStatus.UNAUTHORIZED);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneralException(Exception ex) {
return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
6.5.2 自定义拒绝访问处理
当用户访问受保护的资源但未通过身份验证或授权时,Spring Security会返回默认的错误页面。可以自定义拒绝访问处理逻辑,返回JSON格式的错误信息。例如:
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.getWriter().write("{\"message\": \"Access denied\"}");
}
}
在SecurityConfig
类中配置自定义拒绝访问处理:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.access.AccessDeniedHandler;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationFilter jwtAuthenticationFilter;
@Autowired
private AccessDeniedHandler customAccessDeniedHandler;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling()
.accessDeniedHandler(customAccessDeniedHandler);
}
}
七、总结
通过本文的介绍,我们详细阐述了如何在Spring Boot项目中整合Spring Security和JWT认证。首先,我们了解了JWT的基本结构和工作流程,以及Spring Security的核心架构和配置方法。然后,我们逐步实现了JWT的生成、验证和刷新机制,并将其与Spring Security集成,实现了基于JWT的身份验证和授权。最后,我们介绍了错误处理和异常定制的方法,提高了系统的健壮性和用户体验。
在实际应用中,还可以根据具体需求对系统进行进一步的优化和扩展,例如添加角色权限管理、多因素认证等功能。希望本文能帮助你构建一个安全可靠的Spring Boot应用。