gpt4 book ai didi

java - Spring 安全 : bypass @Secured for specific service

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:44:29 24 4
gpt4 key购买 nike

我目前正在我的应用程序中实现 Spring Security。我确实设法在我的服务上添加了 @Secured 注释,即从数据库中获取 getAllUsers() ,只要确定了用户,它就可以正常工作(取决于他的权限,他可以获取或不获取用户列表)。

但我有一个 @Scheduled 方法负责为所有用户编制索引,当它启动时它调用相同的 protected getAllUsers() 方法,并且由于未登录而明显崩溃:我得到以下异常:

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

我目前正在考虑一种可能的解决方案,即使用自定义注释标记内部方法,该注释将由自定义 AccessDecisionVoter 检索,允许调用者调用 protected 方法。

我正在寻找这种用例的最佳实践

最佳答案

因为方法是 @Secured 并且 spring 期望上下文中的安全身份验证对象。这是 AccessDecisionVoter 的工作示例 Spring-security - AccessDecisionVoter-impl wont be invoked

或者如果你有过滤器或 smth 这将取决于用户上下文值这个应该没问题

@Scheduled
public void method() {
try {
ScheduledAuthenticationUtil.configureAuthentication();
// do work
}
catch(Exception e) {
e.printStackTrace();
}
finally {
ScheduledAuthenticationUtil.cleanAuthentication();
}
}


private static class ScheduledAuthenticationUtil {

public static void configureAuthentication() {
// inject auth obj into SecurityContextHolder
}

public static void cleanAuthentication() {
// SecurityContextHolder clean authentication
}
}

关于java - Spring 安全 : bypass @Secured for specific service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30195845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com