前言#
Spring Security
支持方法级别的权限控制。在此机制上,我们可以在任意层的任意方法上加入权限注解,加入注解的方法将自动被Spring Security
保护起来,仅仅允许特定的用户访问,从而还到权限控制的目的, 当然如果现有的权限注解不满足我们也可以自定义
快速开始#
- 首先加入security依赖如下
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.接着新建安全配置类
Spring Security
默认是禁用注解的,要想开启注解,要在继承WebSecurityConfigurerAdapter
的类加@EnableMethodSecurity
注解,并在该类中将AuthenticationManager
定义为Bean。
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(
prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
我们看到@EnableGlobalMethodSecurity
分别有prePostEnabled 、securedEnabled、jsr250Enabled
三个字段,其中每个字段代码一种注解支持,默认为false,true为开启
。那么我们就一一来说一下这三总注解支持。
prePostEnabled = true 的作用的是启用Spring Security的@PreAuthorize 以及@PostAuthorize 注解。
securedEnabled = true 的作用是启用Spring Security的@Secured 注解。
jsr250Enabled = true 的作用是启用@RoleAllowed 注解
更详细使用整合请参考我这两篇
轻松上手SpringBoot+SpringSecurity+JWT实RESTfulAPI权限控制实战