新版本Spring Security 2.7 + 用法,直接旧正版粘贴

一、以前的用法:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Bean
	public PasswordEncoder passwordEncoder(){
		return new BCryptPasswordEncoder();
	}
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
		//关闭csrf
		.csrf().disable()
		//不通过Session获取SecurityContext
		.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
		.and()
		.authorizeRequests()
		// 对于登录接口 允许匿名访问
		.antMatchers("/user/login").anonymous()
		// 除上面外的所有请求全部需要鉴权认证
		.anyRequest().authenticated();
	}
	@Bean
	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}
}

WebSecurityConfigurerAdapter 已经过时了,新版本已经不用这个了。

二、现在的用法

使用@EnableWebSecurity注解

@Configuration
@EnableWebSecurity
public class SecurityConfig{

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

    /**
     * 安全配置
     */
    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/user/login").anonymous()
                .anyRequest().authenticated();
        return http.build();
    }

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

三、其他的一些配置

@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();
    }
}
————————
如觉不错,随手点赞,关注,收藏(* ̄︶ ̄),谢谢~~
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值