【Spring Security】安全框架学习(十四)

该博客介绍了如何在Spring Security中实现基于配置的权限控制。通过在配置类中设置,可以对特定接口如'/test'应用权限,如使用`hasAuthority('test')`。此外,配置还包括了登录接口的匿名访问,HTTP安全设置,异常处理,JWT过滤器的添加以及跨域设置。整体展示了Spring Security的细粒度权限配置方法。
摘要由CSDN通过智能技术生成

6.2 基于配置的权限控制

我们之前的权限控制都是在对应的资源上面,加上注解去进行一个权限的配置。实际上spring security还允许我们在配置类中进行配置权限。例如我们之前就对login接口进行了一个相应的权限控制。

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    //创建BCryptPasswordEncoder注入容器
	@Bean
	public PasswordEncoder passwordEncoder(){
		return new BCryptPasswordEncoder();
    }
    
    @Bean
    @Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			//关闭csrf,前后端分离项目必须写
			.csrf().disable()
			//前后端分离不能使用session,这里不通过session获取SecurityContext
			.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
			.and()
			.authorizeRequests()
			//对于登录接口允许匿名访问
			.antMatchers("/user/login").anonymous()
            //6.2小节新增内容,添加权限控制,根据需要自行添加修改,除了hasAuthority,其他方法也能使用
            .antMatchers("/test").hasAuthority("test")
			//除上面外的所有请求全部需要鉴权认证
			.anyRequest().authenticated();
        
        //配置异常处理器
        http.exceptionHandling()
            //认证失败处理器
            .authenticationEntryPoint (authenticationEntryPoint)
            //授权失败处理器
			.accessDeniedHandler(accessDeniedHandler);
        
                
    //新增加的过滤器代码,需要传入两个对象,一个文档对象,一个字节码对象(指定添加到哪个过滤器对象之前)
    	http
            .addFilterBefore(jwtAuthenticationTokenFilter,UsernamePasswordAuthenticationFilter.class);
        
        //允许跨域
        http.cors();
	}

    
    @Bean
    @Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值