3.8 Spring Security配置方法安全注解

从版本2开始,Spring Security大大增强了对服务层方法添加安全性的支持。它提供了对JSR-250注解以及框架原始的@Secured注解的安全性的支持。从3.0开始你也可以使用新的基于表达式的注解。你可以应用安全性到一个单例bean,使用 intercept-methods 元素去修饰这个bean的声明,或者你可以使用使用AspectJ样式切入点保护整个服务层的多个bean。

3.81 EnableGlobalMethodSecurity

我们可以在任意的@Configuration注解的实例上使用@EnableGobalMethodSecurity注解来启用基于注解的安全配置。例如,下面将启用Spring Security的@Secure注解。

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class MethodSecurityConfig {
// ...
}

在方法上(也可以在类或接口上)添加注解将相应地限制对该方法的访问。Spring Security的本地注解支持为该方法定义了一组属性。这些信息将传递给访问决策管理器(AccessDecisionManager ),以便它做出实际的决定:

public interface BankService {

@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
public Account readAccount(Long id);

@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
public Account[] findAccounts();

@Secured("ROLE_TELLER")
public Account post(Account account, double amount);
}

可以使用以下方法启用对JSR-250注解的支持:

@Configuration
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class MethodSecurityConfig {
// ...
}

这些是基于标准的并允许应用简单的基于角色的约束,但是没有Spring Security的本地注解的支持。若要使用新的基于表达式的语法,请参考以下使用:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig {
// ...
}

和它等价的Java代码是:

public interface BankService {

@PreAuthorize("isAnonymous()")
public Account readAccount(Long id);

@PreAuthorize("isAnonymous()")
public Account[] findAccounts();

@PreAuthorize("hasAuthority('ROLE_TELLER')")
public Account post(Account account, double amount);
}

3.8.2 GlobalMethodSecurityConfiguration

有时你可能需要执行比使用@EnableGlobalMethodSecurity注解允许的操作更复杂的操作。对于这种场景写,我们可以去扩展GlobalMethodSecurityConfiguration确保子类中存在@EnableGlobalMethodSecurity注解。例如,如果你想提供自定义MethodSecurityExpressionHandler处理逻辑,你可以使用以下配置:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        // ... create and return custom MethodSecurityExpressionHandler ...
        return expressionHandler;
    }
}

其他更多有关Spring Security的方法安全注解,请到Spring Security官方文档查看。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,422评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,058评论 6 342
  • 要加“m”说明是MB,否则就是KB了. -Xms:初始值 -Xmx:最大值 -Xmn:最小值 java -Xms8...
    dadong0505阅读 10,343评论 0 53
  • spring官方文档:http://docs.spring.io/spring/docs/current/spri...
    牛马风情阅读 5,703评论 0 3
  • 这个测试有点奇怪,显示出的能顺利的总是方法的最后一种情况。昨晚就开始纠结,网上找了很多资料,一直都找不到合适的解决...
    大大大甘阅读 1,462评论 0 1