Springboot2.7之后如何配置SpringSecurity的jwt配置

时间: 2024-02-18 16:30:32 浏览: 26
Spring Boot 2.7 还没有发布,可能是您想说的是 Spring Boot 2.4。 在 Spring Boot 2.4 中,配置 Spring Security 和 JWT 的步骤如下: 1. 添加依赖 在 pom.xml 文件中添加 Spring Security 和 JWT 的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>0.11.2</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.2</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <version>0.11.2</version> <scope>runtime</scope> </dependency> ``` 2. 配置 Spring Security 在 Spring Security 的配置类中,添加以下代码: ```java @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JwtTokenFilter jwtTokenFilter; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/api/authenticate").permitAll() .anyRequest().authenticated() .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password(passwordEncoder().encode("password")).roles("USER"); } } ``` 这个配置类中,我们首先禁用了 CSRF 防护,然后配置了访问控制,允许 `/api/authenticate` 路径的请求不需要认证,其他路径的请求需要进行认证。同时,我们还配置了使用 JWT 进行认证,通过 `JwtTokenFilter` 过滤器来实现。 3. 配置 JWT 在 JWT 的配置类中,添加以下代码: ```java @Configuration public class JwtConfig { @Value("${jwt.secret}") private String secret; @Bean public JwtParser jwtParser() { return Jwts.parser().setSigningKey(secret); } @Bean public JwtEncoder jwtEncoder() { return Jwts.builder().setSigningKey(secret).build(); } @Bean public JwtTokenFilter jwtTokenFilter() { return new JwtTokenFilter(jwtParser()); } } ``` 在这个配置类中,我们首先从配置文件中读取了 JWT 的密钥,然后配置了 `JwtParser` 和 `JwtEncoder` 对象,用于解析和生成 JWT。最后,我们还配置了 `JwtTokenFilter` 过滤器。这个过滤器用于在每个请求中解析 JWT,并将解析后的信息传递给 Spring Security 进行认证。 4. 编写 JwtTokenFilter 最后,我们需要编写 `JwtTokenFilter` 过滤器。这个过滤器用于在每个请求中解析 JWT,并将解析后的信息传递给 Spring Security 进行认证。具体代码如下: ```java public class JwtTokenFilter extends OncePerRequestFilter { private final JwtParser jwtParser; public JwtTokenFilter(JwtParser jwtParser) { this.jwtParser = jwtParser; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String header = request.getHeader("Authorization"); if (header != null && header.startsWith("Bearer ")) { String token = header.substring(7); try { Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token); String username = claimsJws.getBody().getSubject(); List<SimpleGrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, authorities); SecurityContextHolder.getContext().setAuthentication(authenticationToken); } catch (Exception e) { SecurityContextHolder.clearContext(); } } chain.doFilter(request, response); } } ``` 在这个过滤器中,我们首先从请求头中获取 JWT,然后使用 `JwtParser` 对象对 JWT 进行解析。如果解析成功,我们就从 JWT 中获取用户名,并创建一个 `UsernamePasswordAuthenticationToken` 对象,用于在 Spring Security 中进行认证。最后,我们将认证信息保存到 `SecurityContextHolder` 中,以便于后续的处理。如果解析失败,我们就清空 `SecurityContextHolder` 中的认证信息。

相关推荐

最新推荐

recommend-type

Springboot+SpringSecurity+JWT实现用户登录和权限认证示例

主要介绍了Springboot+SpringSecurity+JWT实现用户登录和权限认证示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

SpringBoot集成SpringSecurity和JWT做登陆鉴权的实现

主要介绍了SpringBoot集成SpringSecurity和JWT做登陆鉴权的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

SpringBoot+Spring Security+JWT实现RESTful Api权限控制的方法

主要介绍了SpringBoot+Spring Security+JWT实现RESTful Api权限控制的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

SpringSecurity Jwt Token 自动刷新的实现

主要介绍了SpringSecurity Jwt Token 自动刷新的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

基于springboot+jwt实现刷新token过程解析

主要介绍了基于springboot+jwt实现刷新token过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

spring添加xml配置文件

1. 创建一个新的Spring配置文件,例如"applicationContext.xml"。 2. 在文件头部添加XML命名空间和schema定义,如下所示: ``` <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。