Reputation: 356
I am studying Spring Security and I am using Spring Security 3.2.7 and have question about servlet integration feature
Refer to Spring documentation
3.1.3. HttpServletRequest.isUserInRole(String)
The HttpServletRequest.isUserInRole(String) will determine if SecurityContextHolder.getContext().getAuthentication().getAuthorities() contains a GrantedAuthority with the role passed into isUserInRole(String).
Typically users should not pass in the "ROLE_" prefix into this method since it is added automatically. For example, if you want to determine if the current user has the authority "ROLE_ADMIN", you could use the the following:
boolean isAdmin = httpServletRequest.isUserInRole("ADMIN");
This might be useful to determine if certain UI components should be displayed. For example, you might display admin links only if the current user is an admin.
However, when I tried, I found that httpServletRequest.isUserInRole("ADMIN"); return false, while httpServletRequest.isUserInRole("ROLE_ADMIN"); return true.
Is there any special configuration require to have "ROLE_" prefix automatically added when calling isUserInRole ?
Below is my configuration (from sample application)
<authentication-manager>
<authentication-provider>
<user-service>
<user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="bob" password="bobspassword" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
Upvotes: 0
Views: 2234
Reputation: 356
I have found a solution for this. By comparing the source code of class org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper between Spring Security 3.2.7 and 4.0.1 I found that in 4.0.1 the property rolePrefix is initialized with the value "ROLE_" but not in 3.2.7.
Spring Security 3.2.7
private final String rolePrefix;
Spring Security 4.0.1
private String rolePrefix = "ROLE_";
So it does seem that the prefix "ROLE_" is not automatically added for Spring Security 3.2.7
And with the example from Migrating from Spring Security 3.x to 4.x (XML Configuration), I have created a BeanPostProcessor to set "ROLE_" to rolePrefix property of SecurityContextHolderAwareRequestFilter.
public class DefaultRolesPrefixPostProcessor implements BeanPostProcessor, PriorityOrdered {
...
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof SecurityContextHolderAwareRequestFilter) {
SecurityContextHolderAwareRequestFilter filter = (SecurityContextHolderAwareRequestFilter) bean;
filter.setRolePrefix("ROLE_");
}
return bean;
}
}
Above solution works for my case, but I am not sure whether this is the correct way to do this.
Upvotes: 2