Spring安全性为所有角色名称添加了前缀“ROLE_”?

我在Web Security Config中有这个代码:

@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/api/**") .hasRole("ADMIN") .and() .httpBasic().and().csrf().disable(); } 

所以我在我的数据库中添加了一个具有“ADMIN”角色的用户,当我尝试使用此用户登录时,我总是得到403错误,然后我启用了spring for log,我找到了这一行:

 2015-10-18 23:13:24.112 DEBUG 4899 --- [nio-8080-exec-1] osswaiFilterSecurityInterceptor : Secure object: FilterInvocation: URL: /api/user/login; Attributes: [hasRole('ROLE_ADMIN')] 

为什么Spring Security正在寻找“ROLE_ADMIN”而不是“ADMIN”?

Spring安全性默认添加前缀“ ROLE_ ”。

如果您想删除或更改此内容,请查看

http://forum.spring.io/forum/spring-projects/security/51066-how-to-change-role-from-interceptor-url

编辑:发现这一点: Spring Security删除RoleVoter前缀

在Spring 4中,有两个方法hasAuthority()hasAnyAuthority()org.springframework.security.access.expression.SecurityExpressionRoot类中定义。 这两种方法仅检查您的自定义角色名称, 而不添加ROLE_前缀。 定义如下:

 public final boolean hasAuthority(String authority) { return hasAnyAuthority(authority); } public final boolean hasAnyAuthority(String... authorities) { return hasAnyAuthorityName(null, authorities); } private boolean hasAnyAuthorityName(String prefix, String... roles) { Set roleSet = getAuthoritySet(); for (String role : roles) { String defaultedRole = getRoleWithDefaultPrefix(prefix, role); if (roleSet.contains(defaultedRole)) { return true; } } return false; } private static String getRoleWithDefaultPrefix(String defaultRolePrefix, String role) { if (role == null) { return role; } if (defaultRolePrefix == null || defaultRolePrefix.length() == 0) { return role; } if (role.startsWith(defaultRolePrefix)) { return role; } return defaultRolePrefix + role; } 

用法示例:

                 

由于@olyanren很难过,你可以在Spring 4中使用hasAuthority()方法而不是hasRole()。 我正在添加JavaConfig示例:

 @Override protected void configure(HttpSecurity http) throws Exception { .authorizeRequests() .antMatchers("/api/**") .access("hasAuthority('ADMIN')") .and() .httpBasic().and().csrf().disable(); }