[英]Spring Security @PreAuthorize ByPass for specifc role
我正在使用 Spring 安全策略,需要全局角色SUPER的幫助,當令牌擁有它時,它必須繞過端點上的所有@PreAuthorize
。 這是一個端點示例:
@GetMapping
@PreAuthorize("(hasAuthority('DOMAIN_FIND_ALL'))")
public ResponseEntity<ResponseDTO<List<DomainDTO>>> findAll() {
return ResponseEntity.ok().body(domainService.findAll());
}
我為我的全球角色找到的工作方式是這樣的
@GetMapping
@PreAuthorize("(hasAuthority('DOMAIN_FIND_ALL') or (hasAuthority('SUPER'))")
public ResponseEntity<ResponseDTO<List<DomainDTO>>> findAll() {
return ResponseEntity.ok().body(domainService.findAll());
}
但是實現應用程序的每個端點都太長了(hasAuthority('SUPER')
,所以我正在尋找一種以全局方式配置它的方法,這樣,如果令牌具有該角色,則允許所有端點.
我試過的:
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.otherStuffs..
.antMatchers("/**").authenticated()
.antMatchers("/**").hasRole("SUPER");
}
但它不起作用。 有人對此有任何想法嗎?
有關更詳細的說明,請查看以下鏈接(主要是第 6 節)。 用作我回復基礎的代碼是:
CustomMethodSecurityExpressionHandler
以下代碼適用於我:
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.otherStuffs..
.antMatchers("/**").authenticated(); // hasRole("SUPER") isn't require
}
覆蓋默認的MethodSecurityExpressionOperations
接口:
public class MySecurityExpressionRoot implements MethodSecurityExpressionOperations {
// Same properties than provided
// link for MySecurityExpressionRoot
...
public MySecurityExpressionRoot(Authentication authentication) {
if (authentication == null) {
throw new IllegalArgumentException("Authentication object cannot be null");
}
this.authentication = authentication;
}
// This is the ONLY change, as you can see the "SUPER" was added as allowed
@Override
public final boolean hasAuthority(String authority) {
return this.hasAnyAuthority(authority, "SUPER");
}
// Rest of the code is the same than provided
// link for MySecurityExpressionRoot
...
}
現在我們需要將上面的 class 添加到 Spring 配置中:
@Configuration // Required although not include in "source CustomMethodSecurityExpressionHandler" class
public class CustomMethodSecurityExpressionHandler extends DefaultMethodSecurityExpressionHandler {
private final AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
@Override
protected MethodSecurityExpressionOperations createSecurityExpressionRoot(Authentication authentication, MethodInvocation invocation) {
final MySecurityExpressionRoot root = new MySecurityExpressionRoot(authentication);
root.setPermissionEvaluator(getPermissionEvaluator());
root.setTrustResolver(this.trustResolver);
root.setRoleHierarchy(getRoleHierarchy());
return root;
}
}
現在您可以使用以下虛擬GET
端點對其進行驗證:
@GetMapping("/add-new-user")
@PreAuthorize("hasAuthority('ADMIN')")
public ResponseEntity<String> addNewUser() {
return new ResponseEntity("[add-new-user] Testing purpose", OK);
}
任何具有: ADMIN
或SUPER
角色的用戶都可以訪問它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.