Spring Seucurity 有关注解

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@EnableGlobalAuthentication – 启用全局认证机制

用在某个类上,然后这个类就变成了一个配置类,并且可以使用该配置类定制一个全局的AuthenticationManagerBuilder实例用于构建AuthenticationManager

如果在一个没有使用注解@EnableGlobalAuthentication的类中自定义全局AuthenticationManagerBuilder`实例,可能会引起不可预料的结果。

@EnableGlobalAuthentication = @Configuration + AuthenticationConfiguration

@EnableGlobalMethodSecurity – 启用全局方法安全注解机制

缺省情况下,Spring Security并不打开方法层面的安全注解机制,要想使用方法层面的安全注解,需要使用@EnableGlobalMethodSecurityWeb控制器类上。

这里所提到的方法层面的安全注解指的是 :

  • @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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值