提问者:小点点

Spring security@PreAuthorize不工作


我有工作基本的安全示例,现在我需要在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的用户也可以访问 /adminAPI,ROLE_ADMIN的用户也可以访问 /userAPI,我用过


共1个答案

匿名用户

权威和角色导致混乱。

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

hasPower('ROLE_USER')类似于hasRole('USER'),因为'ROLE_'前缀会自动添加。