@EnableGlobalAuthentication
– 启用全局认证机制
用在某个类上,然后这个类就变成了一个配置类,并且可以使用该配置类定制一个全局的AuthenticationManagerBuilder
实例用于构建AuthenticationManager
。
如果在一个没有使用注解@EnableGlobalAuthentication
的类中自定义全局
AuthenticationManagerBuilder`实例,可能会引起不可预料的结果。
@EnableGlobalAuthentication
= @Configuration
+ AuthenticationConfiguration
@EnableGlobalMethodSecurity
– 启用全局方法安全注解机制
缺省情况下,Spring Security
并不打开方法层面的安全注解机制,要想使用方法层面的安全注解,需要使用@EnableGlobalMethodSecurity
在Web
控制器类上。
这里所提到的方法层面的安全注解指的是 :
@PreAuthorize
– 方法调用之前的授权控制,基于表达式计算结果来限制对方法的访问@PostAuthorize
– 方法调用之后的授权控制,允许方法调用,但如果表达式计算结果为false
,将抛出一个安全异常@PreFilter
– 在方法调用前对方法集合类型的参数进行过滤,剔除表达式计算为false
的元素@PostFilter
– 当方法返回结果是集合类型时,在方法调用后对返回结果进行过滤,剔除表达式计算为false
的元素
如果想对方法层面安全做更多的自定义,可以扩展
GlobalMethodSecurityConfiguration
。
@EnableGlobalMethodSecurity
= @EnableGlobalAuthentication
+ GlobalMethodSecuritySelector
@EnableWebSecurity
– 启用Web
安全机制
配置类上使用该注解,同时实现接口WebSecurityConfigurer
或者继承WebSecurityConfigurerAdapter
用于配置Spring Web
应用的安全:
@Configuration
@EnableWebSecurity
public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
// Spring Security should completely ignore URLs starting with /resources/
.antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/public/**").permitAll().anyRequest()
.hasRole("USER").and()
// Possibly more configuration ...
.formLogin() // enable form based log in
// set permitAll for all URLs associated with Form Login
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
// enable in memory based authentication with a user named "user" and "admin"
.inMemoryAuthentication().withUser("user").password("password").roles("USER")
.and().withUser("admin").password("password").roles("USER", "ADMIN");
}
// Possibly more overridden methods ...
}
@EnableWebSecurity
= @EnableGlobalAuthentication
+ WebSecurityConfiguration
+ SpringWebMvcImportSelector
+ OAuth2ImportSelector