Spring Seucurity 有关注解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/andy_zhang2007/article/details/88560499

@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

猜你喜欢

转载自blog.csdn.net/andy_zhang2007/article/details/88560499
今日推荐