如何使用 JavaConfig 从 Spring Security 中删除 ROLE_ 前缀? [英] How do I remove the ROLE_ prefix from Spring Security with JavaConfig?

查看:39
本文介绍了如何使用 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/迁移/当前/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_ 前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆