springboot2.7.x版本集成JWT+spring security推荐写法(WebSecurityConfigurerAdapter过期了) weir 2022-03-13 13:09:13.0 spring security 1458 springboot2.7.x版本集成JWT+spring security推荐写法,WebSecurityConfigurerAdapter过期了你在推荐使用而是换了实现方式  先看下老写法: ```java package com.yaken.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; // 开启方法注解功能 //@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) //@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private JWTAuthenticationManager jwtAuthenticationManager; @Override protected void configure(HttpSecurity http) throws Exception { // restful具有先天的防范csrf攻击,所以关闭这功能 http.csrf().disable().authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // .anyRequest().permitAll() .antMatchers("/actuator/**").permitAll() .antMatchers("/login").permitAll() .antMatchers("/send_sms_code").permitAll() .antMatchers("/check_sms_code").permitAll() .antMatchers("/update_pwd").permitAll() .antMatchers("/init_perm").permitAll() // swagger start .antMatchers("/swagger-ui/").permitAll().antMatchers("/swagger-resources/**").permitAll() .antMatchers("/swagger-ui.html").permitAll().antMatchers("/swagger-resources/**").permitAll() .antMatchers("/images/**").permitAll().antMatchers("/webjars/**").permitAll() .antMatchers("/v2/api-docs").permitAll().antMatchers("/configuration/ui").permitAll() .antMatchers("/v3/api-docs").permitAll().antMatchers("/configuration/ui").permitAll() .antMatchers("/configuration/security").permitAll() .antMatchers("/v3/api-docs/**").permitAll() .antMatchers("/swagger-ui/**").permitAll() // swagger end .anyRequest().authenticated().and() // 添加属于我们自己的过滤器,注意因为我们没有开启formLogin(),所以UsernamePasswordAuthenticationFilter根本不会被调用 .addFilterAt(new JWTAuthenticationFilter(jwtAuthenticationManager), UsernamePasswordAuthenticationFilter.class) // 前后端分离本身就是无状态的,所以我们不需要cookie和session这类东西。所有的信息都保存在一个token之中。 .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } @Override public void configure(WebSecurity web) { web.ignoring().antMatchers("/static/**"); web.ignoring().antMatchers("/**/*.js", "/**/*.json", "/**/*.css", "/**/*.js", "/**/*.map", "/**/*.png", "/**/*.html", "/**/*.jpg", "/**/*.svg", "/**/*.ico"); } } ``` 新写法为: ```java package com.yaken.security; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import com.nimbusds.jose.jwk.JWK; import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jose.jwk.source.ImmutableJWKSet; import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.proc.SecurityContext; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtEncoder; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; import org.springframework.security.oauth2.jwt.NimbusJwtEncoder; import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint; import org.springframework.security.oauth2.server.resource.web.access.BearerTokenAccessDeniedHandler; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration public class SecurityConfigNew { @Autowired private JWTAuthenticationManager jwtAuthenticationManager; @Value("${jwt.public.key}") RSAPublicKey key; @Value("${jwt.private.key}") RSAPrivateKey priv; @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { // @formatter:off http .authorizeHttpRequests((authorize) -> authorize .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // .anyRequest().permitAll() .antMatchers("/actuator/**").permitAll() .antMatchers("/login").permitAll() .antMatchers("/send_sms_code").permitAll() .antMatchers("/check_sms_code").permitAll() .antMatchers("/update_pwd").permitAll() .antMatchers("/init_perm").permitAll() // swagger start .antMatchers("/swagger-ui/").permitAll().antMatchers("/swagger-resources/**").permitAll() .antMatchers("/swagger-ui.html").permitAll().antMatchers("/swagger-resources/**").permitAll() .antMatchers("/images/**").permitAll().antMatchers("/webjars/**").permitAll() .antMatchers("/v2/api-docs").permitAll().antMatchers("/configuration/ui").permitAll() .antMatchers("/v3/api-docs").permitAll().antMatchers("/configuration/ui").permitAll() .antMatchers("/configuration/security").permitAll() .antMatchers("/v3/api-docs/**").permitAll() .antMatchers("/swagger-ui/**").permitAll() .anyRequest().authenticated() ) .csrf().disable() .addFilterAt(new JWTAuthenticationFilter(jwtAuthenticationManager), UsernamePasswordAuthenticationFilter.class) .httpBasic(Customizer.withDefaults()) .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt) .sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .exceptionHandling((exceptions) -> exceptions .authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint()) .accessDeniedHandler(new BearerTokenAccessDeniedHandler()) ); // @formatter:on return http.build(); } @Bean JwtDecoder jwtDecoder() { return NimbusJwtDecoder.withPublicKey(this.key).build(); } @Bean JwtEncoder jwtEncoder() { JWK jwk = new RSAKey.Builder(this.key).privateKey(this.priv).build(); JWKSource jwks = new ImmutableJWKSet<>(new JWKSet(jwk)); return new NimbusJwtEncoder(jwks); } } ``` 当然配置文件我不能直接发出来:  大家可以去官方demo下载:https://github.com/spring-projects/spring-security-samples/blob/5.6.x/servlet/spring-boot/java/jwt/login/src/main/java/example/RestConfig.java 其他我就不多说了,如果你之前在使用JWT我相信你是能看懂的,就这么一点点改变就可以切换到2.7.版本了。