🎓博主介绍:Java、Python、js全栈开发 “多面手”,精通多种编程语言和技术,痴迷于人工智能领域。秉持着对技术的热爱与执着,持续探索创新,愿在此分享交流和学习,与大家共进步。
📖DeepSeek-行业融合之万象视界(附实战案例详解100+)
📖全栈开发环境搭建运行攻略:多语言一站式指南(环境搭建+运行+调试+发布+保姆级详解)
👉感兴趣的可以先收藏起来,希望帮助更多的人
SpringBoot安全模块实战:整合SpringSecurity与JWT实现权限控制
一、引言
在当今的Web应用开发中,安全性是至关重要的。Spring Boot作为一个流行的Java开发框架,为开发者提供了便捷的开发体验。而Spring Security是Spring家族中用于提供身份验证和授权的强大框架,JSON Web Token(JWT)则是一种用于在网络应用中安全传输信息的开放标准。本文将详细介绍如何在Spring Boot项目中整合Spring Security与JWT,实现高效的权限控制。
二、环境准备
2.1 开发工具
- IntelliJ IDEA:一款功能强大的Java集成开发环境。
- Maven:用于项目的依赖管理和构建。
2.2 技术栈
- Spring Boot 2.x
- Spring Security
- JSON Web Token(JWT)
2.3 创建Spring Boot项目
可以使用Spring Initializr(https://start.spring.io/)快速创建一个Spring Boot项目,添加以下依赖:
<dependencies>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- JJWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>
三、JWT简介
3.1 什么是JWT
JSON Web Token(JWT)是一种用于在网络应用中安全传输信息的开放标准(RFC 7519)。它由三部分组成:头部(Header)、载荷(Payload)和签名(Signature)。
- 头部(Header):包含令牌的类型(通常是JWT)和使用的签名算法。
- 载荷(Payload):包含声明(Claims),声明是关于实体(通常是用户)和其他数据的声明。
- 签名(Signature):用于验证消息在传输过程中没有被更改,并且在使用私钥签名的情况下,还可以验证JWT的发送者的身份。
3.2 JWT的优点
- 无状态:JWT不需要在服务端存储会话信息,因此可以很容易地实现分布式系统。
- 跨域支持:JWT可以在不同的域名之间使用,方便实现跨域认证。
- 安全性高:通过签名验证,确保数据的完整性和真实性。
四、Spring Security简介
4.1 什么是Spring Security
Spring Security是Spring家族中用于提供身份验证和授权的强大框架。它提供了一系列的过滤器和拦截器,用于处理用户的认证和授权请求。
4.2 Spring Security的核心概念
- 认证(Authentication):验证用户的身份,确定用户是否是其所声称的用户。
- 授权(Authorization):确定用户是否有权限访问某个资源。
五、整合Spring Security与JWT
5.1 创建JWT工具类
创建一个JWT工具类,用于生成和验证JWT令牌:
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
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 {
private static final String SECRET_KEY = "your_secret_key";
private static final long EXPIRATION_TIME = 1000 * 60 * 60 * 10; // 10 hours
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return createToken(claims, userDetails.getUsername());
}
private String createToken(Map<String, Object> claims, String subject) {
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
}
public String extractUsername(String token) {
return extractClaims(token).getSubject();
}
public Date extractExpiration(String token) {
return extractClaims(token).getExpiration();
}
private Claims extractClaims(String token) {
return Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody();
}
private Boolean isTokenExpired(String token) {
return extractExpiration(token).before(new Date());
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
}
5.2 创建自定义UserDetailsService
创建一个自定义的UserDetailsService,用于从数据库中加载用户信息:
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 这里可以从数据库中加载用户信息
if ("admin".equals(username)) {
return new User("admin", "$2a$10$slYQmyNdGzTn7ZLBXBChFOC9f6kFjAqPhccnP6DxlWXx2lPk1C3G6", new ArrayList<>());
} else {
throw new UsernameNotFoundException("User not found");
}
}
}
5.3 创建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.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 JwtRequestFilter extends OncePerRequestFilter {
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
private JwtUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String authorizationHeader = request.getHeader("Authorization");
String username = null;
String jwt = null;
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
jwt = authorizationHeader.substring(7);
try {
username = jwtUtil.extractUsername(jwt);
} 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(jwt, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
chain.doFilter(request, response);
}
}
5.4 配置Spring Security
创建一个配置类,用于配置Spring Security:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.config.http.SessionCreationPolicy;
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 CustomUserDetailsService userDetailsService;
@Autowired
private JwtRequestFilter jwtRequestFilter;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests().antMatchers("/authenticate").permitAll()
.anyRequest().authenticated()
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
}
5.5 创建认证接口
创建一个认证接口,用于生成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.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
private JwtUtil jwtUtil;
@PostMapping("/authenticate")
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 定义角色和权限
在Spring Security中,可以使用角色和权限来进行细粒度的权限控制。例如,定义两个角色:ADMIN和USER,ADMIN具有所有权限,USER只能访问部分资源。
6.2 配置权限控制
在SecurityConfig类中,修改configure方法,添加权限控制:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests().antMatchers("/authenticate").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
.anyRequest().authenticated()
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
6.3 创建受保护的接口
创建一些受保护的接口,验证权限控制:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AdminController {
@GetMapping("/admin/hello")
public String adminHello() {
return "Hello, Admin!";
}
}
@RestController
public class UserController {
@GetMapping("/user/hello")
public String userHello() {
return "Hello, User!";
}
}
七、测试与验证
7.1 启动项目
使用IntelliJ IDEA启动Spring Boot项目。
7.2 进行认证
使用Postman或其他工具,发送POST请求到/authenticate接口,请求体如下:
{
"username": "admin",
"password": "admin"
}
如果认证成功,将返回一个JWT令牌。
7.3 访问受保护的接口
在请求头中添加Authorization字段,值为Bearer <token>,然后访问受保护的接口,验证权限控制。
八、总结
通过整合Spring Security与JWT,我们可以在Spring Boot项目中实现高效的权限控制。JWT的无状态特性和Spring Security的强大功能相结合,为Web应用提供了可靠的安全保障。在实际开发中,可以根据需求进一步扩展和优化权限控制逻辑。


1100

被折叠的 条评论
为什么被折叠?



