Spring Security hasAnyRole无法正常工作 [英] Spring Security hasAnyRole not working
问题描述
我正在使用Spring安全身份验证和MongoDB开发一个应用程序。身份验证方法工作正常,但只能使用 ROLE_ADMIN
。我需要身份验证的所有方法都使用以下注释:
I´m developing an application with spring security authentication and MongoDB. The authentication method is working fine but only with ROLE_ADMIN
. All methods that I need authentication for are annotated with:
@PreAuthorize(hasAnyRole('ROLE_ADMIN','ROLE_USER'))
当我尝试使用 ROLE_USER
的用户进行身份验证时,我总是获得访问被拒绝的错误。
When I try to authenticate with a user that has ROLE_USER
I always get access declined error.
我的春季安全配置是:
<security:global-method-security pre-post-annotations="enabled" />
<security:http auto-config="true" use-expressions="true">
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/logout" access="permitAll" />
<intercept-url pattern="/admin/**"
access="hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')" />
<security:form-login login-page="/login" default-target-url="/admin/main"
authentication-failure-url="/accessdenied" />
<security:logout logout-success-url="/logout" />
<security:session-management>
<security:concurrency-control error-if-maximum-exceeded="true"
max-sessions="1"/>
</security:session-management>
</security:http>
如果我使用:
<intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')" />
我的访问被拒绝 ROLE_ADMIN
和 ROLE_USER
。
如果我使用:
<intercept-url pattern="/admin/**" access="hasAnyRole('ROLE_ADMIN', 'ROLE_USER')" />
我可以使用 ROLE_ADMIN
用户登录但我不能用 ROLE_USER
。
I can log in with a ROLE_ADMIN
user but I can´t with ROLE_USER
.
和我的 LoginService
我有:
public UserDetails loadUserByUsername(String email)
throws UsernameNotFoundException {
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
User user = getUserDetail(email);
userdetails = new org.springframework.security.core.userdetails.User(
user.getEmail(), user.getPwd(), enabled,
accountNonExpired, credentialsNonExpired, accountNonLocked,
getAuthorities(user.getIsAdmin()));
return userdetails;
}
public List<GrantedAuthority> getAuthorities(Integer role) {
List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
if (role.intValue() == 0) {
authList.add(new SimpleGrantedAuthority("ROLE_USER"));
} else if (role.intValue() == 1) {
authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
System.out.println(authList);
return authList;
}
我缺少什么?
推荐答案
当遇到这种问题时,请先尝试添加许多 System.out.println
(或调试日志)要查看您的方法是否正常工作,还要更改:
When you have this kind of problem, please try first adding many System.out.println
(or debug log) to see if your method is working, also change:
hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')
hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')
并检查 role.intValue()== 0
使用 sysout
打印 true
。
这篇关于Spring Security hasAnyRole无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!