Spring Boot整合Spring Security简记-方
2018-01-27 本文已影响146人
78240024406c
new無语 转载请注明原创出处,谢谢!
EnableGlobalMethodSecurity
我们可以在任何@Configuration
类上添加@EnableGlobalMethodSecurity
注解来启动基于注解的安全功能。
- 启动
@Secured
注解
@Secured
方式我测试了一下,不支持分层角色验证。只能验证当前角色。我目前用的是4.2.3版本。不知道是这样设计的还是以后会调整。等后面看源码的时候再进行解析一下吧。
@EnableGlobalMethodSecurity(securedEnabled = true)
然后在方法(类或接口)上添加注释,添加请求该方法的限制。这些将被传递到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注解
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public interface BankService {
@RolesAllowed("ROLE_TELLER")
public Account post(Account account, double amount);
}
- 启用基于表达式的语法验证
@EnableGlobalMethodSecurity(prePostEnabled = true)
-
@PreAuthorize
在方法调用之前,基于表达式的计算结果来限制对方法的访问 -
@PostAuthorize
允许方法调用,但是如果表达式计算结果为false,将抛出一个安全性异常 -
@PostFilter
允许方法调用,但必须按照表达式来过滤方法的结果 -
@PreFilter
允许方法调用,但必须在进入方法之前过滤输入值
等效代码
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);
}
GlobalMethodSecurityConfiguration
有些情况你可以还需要比@EnableGlobalMethodSecurity
功能更复杂的操作。可以通过扩展GlobalMethodSecurityConfiguration
来提供自定义MethodSecurityExpressionHandler
。
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
// ... create and return custom MethodSecurityExpressionHandler ...
return expressionHandler;
}
}