我試圖刪除Spring安全中的「ROLE_」前綴。我想的第一件事是:如何使用JavaConfig從Spring Security中刪除ROLE_前綴?
http.servletApi().rolePrefix("");
那沒有工作,所以我試圖創建一個BeanPostProcessor
爲http://docs.spring.io/spring-security/site/migrate/current/3-to-4/html5/migrate-3-to-4-jc.html#m3to4-role-prefixing-disable建議。那也行不通。
最後,我想創造我自己的SecurityExpressionHandler
:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.expressionHandler(webExpressionHandler())
.antMatchers("/restricted").fullyAuthenticated()
.antMatchers("/foo").hasRole("mycustomrolename")
.antMatchers("/**").permitAll();
}
private SecurityExpressionHandler<FilterInvocation> webExpressionHandler() {
DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
defaultWebSecurityExpressionHandler.setDefaultRolePrefix("");
return defaultWebSecurityExpressionHandler;
}
不過,這並不能工作。如果我使用「hasAuthority(roleName)」而不是hasRole
,它按預期工作。
是否可以從Spring Security的hasRole檢查中刪除ROLE_前綴?
奇怪了'BeanPostProcessor'對我的作品(你沒有聲明它作爲一個'static' bean方法,其中包括了'PriorityOrdered',使其運行速度非常早?)和相同的表達處理器。我們還有一個'DefaultMethodSecurityExpressionHandler'DefaultMethodSecurityExpressionHandler'配置了前綴'null'。 –
是的,我直接從文檔中複製了'BeanPostProcessor'的代碼。我試着將'@ Bean'放入Spring Security的'@ Configuration'類和'@ SpringBootApplication'類中。我添加了一個'System.out.println'來確保它在Spring Security之前被配置。 'hasAuthority'按預期工作,所以我想我會用它來代替。 –
我們有一個非彈簧啓動應用程序。難道這是干擾,或者啓動的安全性在某種程度上還是配置較早? –