Spring Security @PreAuthorize不起作用

时间:2018-11-25 06:58:59

标签: spring security methods

我有一个基本的安全示例,现在我需要在API级别添加@PreAuthorize。在我的控制器中

@RequestMapping(value = "/user", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_USER')")
public Data userHome() {
    Data d = new Data();
    d.setName("user");
    d.setRollNo(5);
    d.setD(new Date());
    return d;
}

@RequestMapping(value = "/admin", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Data adminHome() {
    Data d = new Data();
    d.setName("admin");
    d.setRollNo(2);
    return d;
}

spring安全配置如下

    <beans:beans xmlns="http://www.springframework.org/schema/security"
        xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/security
            http://www.springframework.org/schema/security/spring-security.xsd">
        <global-method-security pre-post-annotations="enabled" />
        <http auto-config="true" use-expressions="true">
            <logout delete-cookies="JSESSIONID" />
            <remember-me />
            <intercept-url pattern="/*" access="isAuthenticated()" />
        </http>
        <debug />
        <authentication-manager>
            <authentication-provider>
                <user-service id="userService">
                    <user name="admin" password="{noop}admin" authorities="ROLE_ADMIN" />
                <user name="user" password="{noop}user" authorities="ROLE_USER" />
                </user-service>
            </authentication-provider>
        </authentication-manager>
        <beans:bean id="passwordEncoder"
   class="org.springframework.security.crypto.password.NoOpPasswordEncoder"
            factory-method="getInstance" />
        <beans:bean id="loggerListener" class="org.springframework.security.authentication.event.LoggerListener" />
    </beans:beans>

身份验证工作正常,问题在于即使具有ROLE_USER的用户也可以访问/ admin API,具有ROLE_ADMIN的用户也可以访问/ user API,我已经使用过<global-method-security pre-post-annotations="enabled"/>,但它似乎可以正常工作,我还想念什么?

1 个答案:

答案 0 :(得分:0)

权威角色会引起混淆。

您应该使用@PreAuthorize("hasRole('USER')")@PreAuthorize("hasAuthority('ROLE_USER')")

hasAuthority(‘ROLE_USER’)hasRole(‘USER’)类似,因为会自动添加“ ROLE_”前缀