從版本2開(kāi)始阔加,Spring Security大大增強(qiáng)了對(duì)服務(wù)層方法添加安全性的支持耐量。它提供了對(duì)JSR-250注解以及框架原始的@Secured注解的安全性的支持糜俗。從3.0開(kāi)始你也可以使用新的基于表達(dá)式的注解校翔。你可以應(yīng)用安全性到一個(gè)單例bean弟跑,使用 intercept-methods 元素去修飾這個(gè)bean的聲明,或者你可以使用使用AspectJ樣式切入點(diǎn)保護(hù)整個(gè)服務(wù)層的多個(gè)bean展融。
3.81 EnableGlobalMethodSecurity
我們可以在任意的@Configuration注解的實(shí)例上使用@EnableGobalMethodSecurity注解來(lái)啟用基于注解的安全配置窖认。例如,下面將啟用Spring Security的@Secure注解告希。
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class MethodSecurityConfig {
// ...
}
在方法上(也可以在類或接口上)添加注解將相應(yīng)地限制對(duì)該方法的訪問(wèn)扑浸。Spring Security的本地注解支持為該方法定義了一組屬性。這些信息將傳遞給訪問(wèn)決策管理器(AccessDecisionManager )燕偶,以便它做出實(shí)際的決定:
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);
}
可以使用以下方法啟用對(duì)JSR-250注解的支持:
@Configuration
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class MethodSecurityConfig {
// ...
}
這些是基于標(biāo)準(zhǔn)的并允許應(yīng)用簡(jiǎn)單的基于角色的約束喝噪,但是沒(méi)有Spring Security的本地注解的支持。若要使用新的基于表達(dá)式的語(yǔ)法指么,請(qǐng)參考以下使用:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig {
// ...
}
和它等價(jià)的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
有時(shí)你可能需要執(zhí)行比使用@EnableGlobalMethodSecurity注解允許的操作更復(fù)雜的操作酝惧。對(duì)于這種場(chǎng)景寫,我們可以去擴(kuò)展GlobalMethodSecurityConfiguration確保子類中存在@EnableGlobalMethodSecurity注解伯诬。例如晚唇,如果你想提供自定義MethodSecurityExpressionHandler處理邏輯,你可以使用以下配置:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
// ... create and return custom MethodSecurityExpressionHandler ...
return expressionHandler;
}
}
其他更多有關(guān)Spring Security的方法安全注解盗似,請(qǐng)到Spring Security官方文檔查看哩陕。