之前说过SpringSecurityJWT验证实现:

在上文中SpringSecurity相关配置是通过继承WebSecurityConfigurerAdapter实现的,但是在新的SpringBoot版本(2.7)中,WebSecurityConfigurerAdapter已经被标记为弃用了,在将来的版本中可能就被移除了,因此通过继承此类来配置就不太适合了,替代方案就是通过bean方式配置。

Bean方式替代继承配置适配器

相较于旧配置方式,JWT的过滤器实现、错误处理策略等不受任何影响,具体可以查看上篇文章,configure(WebSecurity)​中的配置内容改变为在WebSecurityCustomizerSecurityFilterChainbean中实现,这里只列一下新的配置类形式,如下:

package top.wteng.security.configuration;

import top.wteng.jwtsecurity.SecurityConstants;
import top.wteng.jwtsecurity.exception.JwtAccessDeniedHandler;
import top.wteng.jwtsecurity.exception.UnAuthorizedExceptionEntryPoint;
import top.wteng.jwtsecurity.filter.JwtAuthorizationFilter;ilter;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;

import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.Collections;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {
    private final String[] unAuthedUrls = new String[]{
            "/user/login",
    };

    /**
    * 不需要验证的接口
    */
    @Bean
    public WebSecurityCustomizer ignoringCustomizer() {
        return web-> web
                .ignoring()
                .antMatchers(unAuthedUrls);
    }

    /**
    * 授权管理的bean
    */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    /**
    * 配置过滤器
    */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationManager authenticationManager) throws Exception {
        http.cors(Customizer.withDefaults())
                .csrf().disable()
                .authorizeRequests(auth -> auth.anyRequest().authenticated())
                .authenticationManager(authenticationManager)
                .addFilter(new JwtAuthorizationFilter(authenticationManager))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling().authenticationEntryPoint(new UnAuthorizedExceptionEntryPoint())
                .accessDeniedHandler(new JwtAccessDeniedHandler());
        return http.build();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        org.springframework.web.cors.CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Collections.singletonList("*"));
        // configuration.setAllowedOriginPatterns(singletonList("*"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "DELETE", "PUT", "OPTIONS"));
        configuration.setExposedHeaders(Collections.singletonList(SecurityConstants.JWT_HEADER));
        configuration.setAllowCredentials(false);
        configuration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}