【问题标题】:Spring Security RestSpring 安全休息
【发布时间】:2014-09-16 01:27:40
【问题描述】:

我有一组通过使用 Spring-data-rest 项目在 Rest 上公开的 Sping 数据存储库。现在我想保护 HTTP,以便只有注册用户才能访问 http://localhost:8080/rest/ 所以为此我将 @Secured(value = { "ROLE_ADMIN" }) 添加到所有存储库中,我还通过指定

来启用安全性
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)

所以现在发生的事情是我去休息,一切都很好 - 我被要求进行身份验证。接下来我要做的是访问我的网站(它使用所有存储库来访问数据库),但我的请求失败了

nested exception is org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext

这是正确的,因为我以匿名用户身份浏览我的网站。

所以我的问题是:有没有办法只为 REST 层提供方法身份验证?对我来说,这听起来像是需要一个新的注释(比如@EnableRestGlobalMethodSecurity@EnableRestSecurity

【问题讨论】:

    标签: spring-security spring-data-rest


    【解决方案1】:

    我不知道这是否会解决您的问题,但是我设法得到了类似的东西,通过为我的特定存储库创建一个事件处理程序为我工作,然后使用 @PreAuthorize 注释检查权限,比如说之前创建。例如:

    @RepositoryEventHandler(Account.class)
    public class AccountEventHandler {
    
        private final Logger logger = LoggerFactory.getLogger(getClass());
    
        @PreAuthorize("isAuthenticated() and (hasRole('ROLE_USER'))")
        @HandleBeforeCreate
        public void beforeAccountCreate(Account account) {
            logger.debug(String.format("In before create for account '%s'",     account.getName()));
        }
    
        @PreAuthorize("isAuthenticated() and (hasRole('ROLE_ADMIN'))")
        @HandleBeforeSave
        public void beforeAccountUpdate(Account account) {
            logger.debug(String.format("In before update for account '%s'", account.getName()));
        //Don't need to add anything to this method, the @PreAuthorize does the job.
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-30
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 2013-08-22
      • 2016-11-09
      • 1970-01-01
      • 2022-01-08
      相关资源
      最近更新 更多