首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring Security Rest

Spring Security Rest
EN

Stack Overflow用户
提问于 2014-09-16 09:27:40
回答 1查看 323关注 0票数 1

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

代码语言:javascript
复制
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)

因此,现在发生的情况是,我转到其余部分,一切都很好-我被要求进行身份验证。我做的下一件事是访问我的网站(它使用所有的存储库来访问数据库),但是我的请求失败了,如下所示

代码语言:javascript
复制
nested exception is org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext

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

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

EN

回答 1

Stack Overflow用户

发布于 2014-09-16 20:01:40

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

代码语言:javascript
复制
@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.
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25859363

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档