本文介绍了如何使用JavaConfig从Spring Security中删除ROLE_前缀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试在Spring Security中删除"ROLE_"前缀.我尝试的第一件事是:

I'm trying to remove the "ROLE_" prefix in Spring Security. The first thing I tried was:

http.servletApi().rolePrefix("");

那没有用,所以我尝试按照 http://docs.spring.io/spring-security/site/migrate/current/3 -to-4/html5/migrate-3-to-4-jc.html#m3to4-role-prefixing-disable .那也不起作用.

That didn't work, so I tried creating a BeanPostProcessor as suggested in http://docs.spring.io/spring-security/site/migrate/current/3-to-4/html5/migrate-3-to-4-jc.html#m3to4-role-prefixing-disable. That didn't work either.

最后,我尝试创建自己的SecurityExpressionHandler:

Finally, I tried creating my own 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,它将按预期工作.

However, this doesn't work either. If I use "hasAuthority(roleName)" instead of hasRole, it works as expected.

是否可以从Spring Security的hasRole检查中删除ROLE_前缀?

Is it possible to remove the ROLE_ prefix from Spring Security's hasRole check?

推荐答案

从Spring 4.2开始,您可以使用单个bean定义前缀,如下所述: https://github.com/spring-projects/spring-security/issues/4134

Starting from Spring 4.2, you can define the prefix with a single bean, as described here: https://github.com/spring-projects/spring-security/issues/4134

@Bean
GrantedAuthorityDefaults grantedAuthorityDefaults() {
    return new GrantedAuthorityDefaults(""); // Remove the ROLE_ prefix
}

XML版本:

<beans:bean id="grantedAuthorityDefaults" class="org.springframework.security.config.core.GrantedAuthorityDefaults">
    <beans:constructor-arg value="" />
</beans:bean>

这篇关于如何使用JavaConfig从Spring Security中删除ROLE_前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 00:34