基于配置的权限控制
小于 1 分钟Spring全家桶SpringSecurity认证授权
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
@Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private AccessDeniedHandler accessDeniedHandler;
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// 关闭csrf
http.csrf().disable()
// 不通过session获取SecurityContext
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
// 对于登录接口,允许匿名访问
.antMatchers("/user/login").anonymous()
// 配置test接口的权限
.antMatchers("/test").hasAuthority("system:dept:list")
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated();
// 配置认证过滤器在UsernamePasswordAuthenticationFilter之前
http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
http.exceptionHandling()
// 认证失败处理器
.authenticationEntryPoint(authenticationEntryPoint)
// 授权异常处理器
.accessDeniedHandler(accessDeniedHandler);
// 允许跨域
http.cors();
}
}
经过测试发现,如果同时使用了上面的类配置权限和使用@PreAuthorize注解,注解配置的优先生效。推荐使用注解进行权限控制。