我有一个用@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。我可以:
什么是正确的方法?
最佳答案
您可以在当前线程和 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/