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();
}
}