Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove the ROLE_ prefix from Spring Security with JavaConfig?

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

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

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.

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;
  }

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

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

like image 793
Matt Raible Avatar asked Jun 30 '16 22:06

Matt Raible


People also ask

How do I restrict URL in Spring Security?

Securing the URLs The most common methods are: authenticated(): This is the URL you want to protect, and requires the user to login. permitAll(): This is used for URL's with no security applied for example css, javascript. hasRole(String role): Restrict to single role.

How do I change my Spring Security username and password?

To configure the default username, password and role, open application. properties file of your Spring Boot project and add the following three properties with the values you prefer. The above properties will change the default username, password and role.

Does Spring Security use default login form?

Spring security secures all HTTP endpoints by default. A user has to login in a default HTTP form. To enable Spring Boot security, we add spring-boot-starter-security to the dependencies.


1 Answers

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 version:

<beans:bean id="grantedAuthorityDefaults" class="org.springframework.security.config.core.GrantedAuthorityDefaults">
    <beans:constructor-arg value="" />
</beans:bean>
like image 118
Antoine Melki Avatar answered Sep 19 '22 06:09

Antoine Melki