@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
本文深入解析Spring Security中的核心注解,包括@EnableGlobalAuthentication、@EnableGlobalMethodSecurity和@EnableWebSecurity,阐述了它们如何分别启动全局认证机制、全局方法安全注解机制和Web安全机制。同时介绍了方法级别的安全注解如@PreAuthorize、@PostAuthorize、@PreFilter和@PostFilter的使用方式,以及如何通过自定义配置类实现更复杂的权限控制。
2240

被折叠的 条评论
为什么被折叠?



