新版SpringSecurity安全配置说明

 更新时间:2023年07月11日 08:30:13   作者:卑微小钟  
这篇文章主要介绍了新版SpringSecurity安全配置说明,在 Spring Security 5.7.0-M2 中,我们弃用了WebSecurityConfigurerAdapter,因为我们鼓励用户转向基于组件的安全配置,需要的朋友可以参考下

新版SpringSecurityConfig

在使用SpringBoot2.7或者SpringSecurity5.7以上版本时,会提示:

在 Spring Security 5.7.0-M2 中,我们弃用了WebSecurityConfigurerAdapter,因为我们鼓励用户转向基于组件的安全配置。

所以之前那种通过继承WebSecurityConfigurerAdapter的方式的配置组件是不行的。

同时也会遇到很多问题,例如:

在向SpringSecurity过滤器链中添加过滤器时(例如:JWT支持,第三方验证),我们需要注入AuthenticationManager对象等问题。

故在此记录一下SpringSecurity的一些基础配置项:

1 网络安全配置,忽略部分路径(如静态文件路径)

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
     return (web) -> web.ignoring().antMatchers("/ignore1", "/ignore2");
}

2 设置中文配置

@Bean
public ReloadableResourceBundleMessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    // 设置中文配置
    messageSource.setBasename("classpath:org/springframework/security/messages_zh_CN");
    return messageSource;
}

3 设置密码编码器

@Bean
@ConditionalOnMissingBean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

4 取消ROLE_ prefix

@Bean
@ConditionalOnMissingBean
public GrantedAuthorityDefaults grantedAuthorityDefaults() {
    // Remove the ROLE_ prefix
    return new GrantedAuthorityDefaults("");
}

5 暴露本地认证管理器(AuthenticationManager)

/**
 * 认证管理器,登录的时候参数会传给 authenticationManager
 */
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
    return authenticationConfiguration.getAuthenticationManager();
}

6 其他配置

import com.example.websocket.chat.security.filer.CustomUsernamePasswordAuthenticationFilter;
import com.example.websocket.chat.security.filer.JwtAuthenticationFilter;
import com.example.websocket.chat.security.handler.*;
import com.example.websocket.chat.security.service.JwtStoreService;
import com.example.websocket.chat.security.service.impl.UserDetailsServiceImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.core.GrantedAuthorityDefaults;
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.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import javax.annotation.Resource;
/**
 * @author zhong
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SpringSecurityConfig {
    @Resource
    private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
    @Resource
    private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
    @Resource
    private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
    @Resource
    private CustomLogoutHandler customLogoutHandler;
    @Resource
    private CustomLogoutSuccessHandler customLogoutSuccessHandler;
    @Resource
    private CustomAccessDeniedHandler customAccessDeniedHandler;
    @Resource
    private SecurityProperties securityProperties;
    @Resource
    private JwtStoreService jwtStoreService;
    @Resource
    private UserDetailsServiceImpl userDetailsService;
    @Resource
    private AuthenticationConfiguration authenticationConfiguration;
    /**
     * 静态文件放行
     */
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().antMatchers(securityProperties.getStaticPaths());
    }
    /**
     * 取消ROLE_前缀
     */
    @Bean
    public GrantedAuthorityDefaults grantedAuthorityDefaults() {
        // Remove the ROLE_ prefix
        return new GrantedAuthorityDefaults("");
    }
    /**
     * 设置密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    /**
     * 设置中文配置
     */
    @Bean
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:org/springframework/security/messages_zh_CN");
        return messageSource;
    }
    /**
     * 认证管理器,登录的时候参数会传给 authenticationManager
     */
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
    /**
     * 设置默认认证提供
     */
    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        final DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }
    /**
     * 安全配置
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationConfiguration authenticationConfiguration) throws Exception {
        // 表单
        http.formLogin()
                // 登录成功处理器
                .successHandler(customAuthenticationSuccessHandler)
                // 登录错误处理器
                .failureHandler(customAuthenticationFailureHandler)
                .and()
                //添加登录逻辑拦截器,不使用默认的UsernamePasswordAuthenticationFilter
                .addFilterBefore(
                        new CustomUsernamePasswordAuthenticationFilter(
                                authenticationManager(),
                                customAuthenticationSuccessHandler,
                                customAuthenticationFailureHandler
                        )
                        , UsernamePasswordAuthenticationFilter.class)
                //添加token验证过滤器
                .addFilterBefore(new JwtAuthenticationFilter(jwtStoreService), LogoutFilter.class);
        //退出
        http
                .logout()
                // URL
                .logoutUrl("/user/logout")
                // 登出处理
                .addLogoutHandler(customLogoutHandler)
                // 登出成功处理
                .logoutSuccessHandler(customLogoutSuccessHandler);
        //拦截设置
        http
                .authorizeRequests()
                //公开以下urls
                .antMatchers(securityProperties.getPublicPaths()).permitAll()
                //其他路径必须验证
                .anyRequest().authenticated();
        //异常处理
        http
                .exceptionHandling()
                // 未登录处理
                .authenticationEntryPoint(customAuthenticationEntryPoint)
                // 无权限处理
                .accessDeniedHandler(customAccessDeniedHandler);
        //关闭session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 关闭cors
        http.cors().disable();
        // 关闭csrf
        http.csrf().disable();
        // 关闭headers
        http.headers().frameOptions().disable();
        return http.build();
    }
}

到此这篇关于新版SpringSecurity安全配置说明的文章就介绍到这了,更多相关SpringSecurity安全配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 基于Java实现简单的身材计算程序

    基于Java实现简单的身材计算程序

    这篇文章主要为大家详细介绍了如何利用Java实现简单的身材计算程序,可以计算身体的体脂率以及BMI数值等,感兴趣的小伙伴可以跟随小编一起学习一下
    2022-12-12
  • Java编程线程间通信与信号量代码示例

    Java编程线程间通信与信号量代码示例

    这篇文章主要介绍了Java编程线程间通信与信号量代码示例,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • Java实现文件上传的方法总结

    Java实现文件上传的方法总结

    这篇文章主要为大家介绍了三种Java实现文件上传的方法,文中的示例代码讲解详细,对我们的学习或工作有一定的借鉴价值,感兴趣的可以了解一下
    2023-04-04
  • Spring Cloud之服务监控turbine的示例

    Spring Cloud之服务监控turbine的示例

    这篇文章主要介绍了Spring Cloud之服务监控turbine的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-05-05
  • Java实现数据脱敏的方法详细讲解

    Java实现数据脱敏的方法详细讲解

    这篇文章主要给大家介绍了关于Java实现数据脱敏的相关资料,数据脱敏是指对某些敏感信息通过脱敏规则进行数据的变形,实现敏感隐私数据的可靠保护,需要的朋友可以参考下
    2023-06-06
  • Java JVM原理与调优_动力节点Java学院整理

    Java JVM原理与调优_动力节点Java学院整理

    JVM是Java Virtual Machine(Java虚拟机)的缩写,JVM是一种用于计算设备的规范,它是一个虚构出来的计算机,是通过在实际的计算机上仿真模拟各种计算机功能来实现的。下面通过本文给大家介绍jvm原理与调优相关知识,感兴趣的朋友一起学习吧
    2017-04-04
  • SpringMVC Mybatis配置多个数据源并切换代码详解

    SpringMVC Mybatis配置多个数据源并切换代码详解

    这篇文章主要介绍了SpringMVC Mybatis配置多个数据源并切换代码详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • TCC分布式事务七种异常情况小结

    TCC分布式事务七种异常情况小结

    这篇文章主要为大家详细介绍了在整个TCC模型过程中可能会出现的七种异常情况,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-11-11
  • SpringBoot使用AES对JSON数据加密和解密的实现方法

    SpringBoot使用AES对JSON数据加密和解密的实现方法

    这篇文章主要介绍了SpringBoot使用AES对JSON数据加密和解密的实现方法,文章通过代码示例介绍的非常详细,对我们的学习或工作有一定的帮助,需要的朋友可以参考下
    2023-08-08
  • JFinal使用ajaxfileupload实现图片上传及预览

    JFinal使用ajaxfileupload实现图片上传及预览

    这篇文章主要为大家详细介绍了JFinal使用ajaxfileupload实现图片上传及预览,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-09-09

最新评论