Java Spring Security hasAnyRole 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25340163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:09:09  来源:igfitidea点击:

Spring Security hasAnyRole not working

javaspringspring-security

提问by EduSantos

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:

我正在开发一个带有 spring 安全身份验证和 MongoDB 的应用程序。身份验证方法工作正常,但仅适用于ROLE_ADMIN. 我需要身份验证的所有方法都用以下注释进行了注释:

@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")

@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")

When I try to authenticate with a user that has ROLE_USERI always get access declined error.

当我尝试向ROLE_USER我总是收到拒绝访问错误的用户进行身份验证时。

My spring security config is:

我的弹簧安全配置是:

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

If I use:

如果我使用:

<intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')" />

I get access denied for both ROLE_ADMINand ROLE_USER.

我的ROLE_ADMIN和都被拒绝访问ROLE_USER

If I use:

如果我使用:

<intercept-url pattern="/admin/**" access="hasAnyRole('ROLE_ADMIN', 'ROLE_USER')" />

I can log in with a ROLE_ADMINuser but I can′t with ROLE_USER.

我可以使用ROLE_ADMIN用户登录,但不能使用ROLE_USER.

and in my LoginServiceI have:

在我的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;
    }

What am I missing?

我错过了什么?

采纳答案by Arturo Volpe

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:

当你遇到这种问题时,请尝试先添加很多System.out.println(或调试日志),看看你的方法是否有效,同时更改:

hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')

for

为了

hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')

And check if the role.intValue() == 0prints truewith a sysout.

并检查role.intValue() == 0打印件是否true带有sysout.

回答by michael875

This

这个

access="hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')

means that both roles must be set the same time and sample code shows that it never happenes, because only one of two roles can be set.

意味着必须同时设置两个角色,示例代码显示它永远不会发生,因为只能设置两个角色之一。

It is different statement from hasAnyRole('ROLE_ADMIN', 'ROLE_USER')which should be true if at least one of these roles is set. Statment hasAnyRoleis like ornot andcondition.

hasAnyRole('ROLE_ADMIN', 'ROLE_USER')如果设置了这些角色中的至少一个,则应该是不同的陈述。声明hasAnyRole就像or不是and条件。