Bootstrap

SecurityConfig最新版本配置,EnableGlobalMethodSecurity已被弃用无法继承WebSecurityConfigurerAdapter

以前旧版本的SecurityConfig代码如下:

package com.java1234.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String URL_WHITELIST[] ={
            "/login",
            "/logout",
            "/captcha",
            "/password",
            "/image/**",
            "/test/**"
    } ;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 开启跨域 以及csrf攻击 关闭
        http
            .cors()
            .and()
            .csrf()
            .disable()

        // 登录登出配置
        .formLogin()
//            .successHandler()
//            .failureHandler()
//        .and()
//            .logout()
//            .logoutSuccessHandler()

        // session禁用配置
        .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)  // 无状态

        // 拦截规则配置
        .and()
        .authorizeRequests()
        .antMatchers(URL_WHITELIST).permitAll()  // 白名单 放行
        .anyRequest().authenticated();


        // 异常处理配置

        // 自定义过滤器配置

    }
}

新版本超全面配置:

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.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;


@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig {


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }


    // 密码编码器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    // 用户详情服务
    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withUsername("user")
             .password(passwordEncoder().encode("password"))
             .roles("USER")
             .build();


        UserDetails admin = User.withUsername("admin")
             .password(passwordEncoder().encode("admin123"))
             .roles("ADMIN")
             .build();


        return new InMemoryUserDetailsManager(user, admin);
    }


    // 安全过滤器链
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
             .authorizeHttpRequests(authorize -> authorize
                    // 允许所有用户访问的路径
                   .requestMatchers("/", "/home", "/about", "/public/**").permitAll()
                    // 要求具有 USER 角色才能访问的路径
                  .requestMatchers("/user/**").hasRole("USER")
                    // 要求具有 ADMIN 角色才能访问的路径
                  .requestMatchers("/admin/**").hasRole("ADMIN")
                    // 其他请求需要认证
                  .anyRequest().authenticated()
               )
             .formLogin(form -> form
                    // 自定义登录页面的 URL
                   .loginPage("/login")
                    // 登录请求的处理 URL
                  .loginProcessingUrl("/login")
                    // 登录成功后的跳转 URL
                  .defaultSuccessUrl("/dashboard")
                    // 允许所有用户访问登录页面
                  .permitAll()
               )
             .logout(logout -> logout
                    // 登出请求的处理 URL
                  .logoutUrl("/logout")
                    // 登出成功后的跳转 URL
                  .logoutSuccessUrl("/login?logout")
                    // 允许所有用户登出
                  .permitAll()
               )
             .exceptionHandling(exception -> exception
                    // 访问被拒绝时的处理页面
                  .accessDeniedPage("/403")
               )
             .csrf(csrf -> csrf
                    // 启用 CSRF 保护,这是默认设置
                  .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
               );


        return http.build();
    }


    // 自定义 CSRF 令牌存储库,使 CSRF 令牌可在客户端脚本中访问
    @Bean
    public CookieCsrfTokenRepository csrfTokenRepository() {
        return CookieCsrfTokenRepository.withHttpOnlyFalse();
    }


    // 可添加其他安全相关的 Bean 或配置,例如自定义认证提供者、认证成功处理器等


    // 自定义认证成功处理器
    @Bean
    public AuthenticationSuccessHandler authenticationSuccessHandler() {
        return new CustomAuthenticationSuccessHandler();
    }


    // 自定义认证失败处理器
    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return new CustomAuthenticationFailureHandler();
    }


    // 自定义认证入口点,处理未认证用户访问受保护资源时的情况
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return new CustomAuthenticationEntryPoint();
    }


    // 自定义访问被拒绝处理器
    @Bean
    public AccessDeniedHandler accessDeniedHandler() {
        return new CustomAccessDeniedHandler();
    }


    // 可以添加自定义的用户详情服务,例如从数据库中获取用户信息
    @Bean
    public UserDetailsService customUserDetailsService() {
        return new CustomUserDetailsService();
    }


    // 可以添加自定义的密码编码器,例如使用不同的加密算法
    @Bean
    public PasswordEncoder customPasswordEncoder() {
        return new CustomPasswordEncoder();
    }


    // 可以添加其他安全相关的过滤器或拦截器
    @Bean
    public Filter customFilter() {
        return new CustomFilter();
    }


    // 以下是上述自定义处理器的示例代码


    // 自定义认证成功处理器
    public static class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
            // 可以在这里添加自定义逻辑,例如记录登录成功日志
            response.sendRedirect("/dashboard");
        }
    }


    // 自定义认证失败处理器
    public static class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
            // 可以在这里添加自定义逻辑,例如记录登录失败日志
            response.sendRedirect("/login?error");
        }
    }


    // 自定义认证入口点
    public static class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
            // 可以在这里添加自定义逻辑,例如返回自定义的错误信息
            response.sendRedirect("/login?unauthorized");
        }
    }


    // 自定义访问被拒绝处理器
    public static class CustomAccessDeniedHandler implements AccessDeniedHandler {
        @Override
        public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
            // 可以在这里添加自定义逻辑,例如返回自定义的错误页面或消息
            response.sendRedirect("/403");
        }
    }


    // 自定义用户详情服务,从数据库中获取用户信息
    public static class CustomUserDetailsService implements UserDetailsService {
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            // 从数据库中查找用户信息,例如使用 JPA 或 JDBC
            // 这里只是一个示例,实际使用时需实现具体的逻辑
            if (username.equals("user")) {
                return User.withUsername(username)
                     .password(passwordEncoder().encode("password"))
                     .roles("USER")
                     .build();
            } else if (username.equals("admin")) {
                return User.withUsername(username)
                     .password(passwordEncoder().encode("admin123"))
                     .roles("ADMIN")
                     .build();
            } else {
                throw new UsernameNotFoundException("User not found");
            }
        }
    }


    // 自定义密码编码器,使用不同的加密算法
    public static class CustomPasswordEncoder implements PasswordEncoder {
        @Override
        public String encode(CharSequence rawPassword) {
            // 使用自定义的加密算法,这里只是一个示例,实际使用时需实现具体的逻辑
            return rawPassword.toString();
        }


        @Override
        public boolean matches(CharSequence rawPassword, String encodedPassword) {
            // 验证密码是否匹配,这里只是一个示例,实际使用时需实现具体的逻辑
            return rawPassword.toString().equals(encodedPassword);
        }


        @Override
        public boolean upgradeEncoding(String encodedPassword) {
            // 判断是否需要升级编码,这里只是一个示例,实际使用时需实现具体的逻辑
            return false;
        }
    }


    // 自定义过滤器,可用于添加额外的安全逻辑
    public static class CustomFilter extends OncePerRequestFilter {
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            // 可以在这里添加自定义的安全逻辑,例如添加额外的认证检查
            filterChain.doFilter(request, response);
        }
    }
}

一起学习,代码仅供参考根据自己需求进行相关配置删改。

;