Spring 安全 : What is the right way to call method secured with @PreAuthorize in background task?

标签 spring spring-security

我有一个用@PreAuthorize 保护的方法

@PreAuthorize("hasRole('ROLE_ADMIN') and (#action.userId != principal.id)")
public void execute(EditAction action)

现在我需要从后台任务调用这个方法。如果我只是运行此代码 - 我会捕获一个异常:

AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext



看来,我需要将所需的身份验证设置为 SecurityContext。我可以:
  • 为后台任务编写一些自定义 AuthenticationToken 。
  • 将 UsernamePasswordAuthenticationToken 与假用户一起使用。
  • 不要在后台任务中使用安全方法。
  • 还有其他建议吗?

  • 什么是正确的方法?

    最佳答案

    您可以在当前线程和 session 中自行注册身份验证 token (如果在 Web 应用程序中使用):

    SecurityContextHolder.getContext().setAuthentication(token);
    session.put(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
    

    只要您添加适当的角色,您就可以为此使用标准的 UsernamePasswordAuthenticationToken。

    关于 Spring 安全 : What is the right way to call method secured with @PreAuthorize in background task?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10331707/

    相关文章:

    spring - 在带有 CORS 的 REST 中使用 Spring 登录时出现问题

    spring-security - 带有 oidc : refresh the tokens 的 Spring Security

    Spring 安全 : How to clear `remember me` cookie programmatically?

    spring-security - 使用 spring-security-oauth2-client 检索 facebook 个人资料信息

    java - 如何使用 MultiValueMap 作为参数创建 URI/URL?

    java - Spring MVC 4 : "application/json" Content Type is not being set correctly

    grails - 自定义过滤器拦截器和Grails spring-security 2.0rc2插件

    Spring Controller 方法执行两次

    java - Jackson:反序列化枚举

    spring - 如何更改找到 bean 的上下文路径