java - Spring 安全。 protected 注释不起作用

标签 java spring spring-mvc spring-security

我有一些问题。我在我的应用程序中使用 spring security,当我标记方法注释 @Secured("ROLE_ADMIN") 时,它不起作用。

@Secured("ROLE_ADMIN")
@RequestMapping(value = "/greeting",produces = "application/json")
public @ResponseBody List<UserEntity> greeting() {
    return userService.getAllCurrentUsers();
}

这个security-config.xml

<global-method-security secured-annotations="enabled" pre-post-annotations="enabled"/>

<http pattern="/resources/**" security="none"/>
<http pattern="/loginSecurity" security="none"/>
<http pattern="/favicon.ico" security="none" />
<http use-expressions="true">
    <intercept-url pattern="/**" access="hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')"/>
    <form-login login-page="/loginSecurity" default-target-url="/workspace"/>
</http>

<authentication-manager>
    <authentication-provider>
        <password-encoder hash="bcrypt" />
        <jdbc-user-service data-source-ref="dataSource"
                           authorities-by-username-query="SELECT userentity.username , roleentity.role_name from userentity
                                                    JOIN userentity_roleentity ON userentity.userid = userentity_roleentity.userlist_userid
                                                    JOIN roleentity ON userentity_roleentity.rolelist_role_name = roleentity.role_name
                                                    WHERE userentity.username = ?"
                           users-by-username-query="SELECT username,pwd,enable FROM userentity where username = ?"/>
    </authentication-provider>
</authentication-manager>

身份验证有效。数据库中的角色是正确的。 此代码也有效。

sec:authorize access="hasRole('ROLE_ADMIN')">
<button onclick="loadHeadRef('workspace','settings')">
  <img src='<spring:url value="/resources/image/settings.png"/>' alt="">Settings</button>
</sec:authorize>

最佳答案

尝试使用@PreAuthorize

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

在 spring-servlet.xml 中添加以下内容

<security:global-method-security
        pre-post-annotations="enabled" secured-annotations="enabled" />
    <mvc:annotation-driven />

关于java - Spring 安全。 protected 注释不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28811404/

相关文章:

Java程序卡在特定线程上

java - 如何修复此问题 'java.io.FileNotFoundException'

java - FacesServlet.service() 方法在服务请求时消耗太多时间(高自耗时间)

java - Spring Boot Repository 与 DAO 中的 API

java - SpringMVC : How to filter the client's IP?

java - 多个安全适配器 - addFilterBefore 未按预期工作

java - 由于类没有状态,因此无需延迟初始化

java - 从 C 驱动器以 Java 代码加载图像

java - 找出谁使用Redis

Spring - 无法解析 MVC "view"thymeleaf