gpt4 book ai didi

spring - 手动获取 AuthenticationManager 实例

转载 作者:行者123 更新时间:2023-12-02 22:53:13 30 4
gpt4 key购买 nike

我正在尝试实现以下内容,但我的authenticationManager实例抛出以下异常并且未 Autowiring 。如何从 Spring 手动获取它的实例?我没有使用 Spring Controller ,而是使用 JSF 请求作用域 bean。当容器尝试 Autowiring authenticationManager 时,我在运行时收到以下异常。 requestCache 来得很好。我不明白为什么我有两个实例......

配置:

<authentication-manager>
<authentication-provider user-service-ref="userManager">
<password-encoder ref="passwordEncoder" />
</authentication-provider>
</authentication-manager>

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected org.springframework.security.authentication.AuthenticationManager com.dc.web.actions.SignUpDetail.authenticationManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [org.springframework.security.authentication.AuthenticationManager] is defined: expected single matching bean but found 2: [org.springframework.security.authentication.ProviderManager#0, org.springframework.security.authenticationManager] javax.faces.webapp.FacesServlet.service(FacesServlet.java:325)

@Controller
public class SignupController
{

@Autowired
RequestCache requestCache;

@Autowired
protected AuthenticationManager authenticationManager;

@RequestMapping(value = "/account/signup/", method = RequestMethod.POST)
public String createNewUser(@ModelAttribute("user") User user, BindingResult result, HttpServletRequest request, HttpServletResponse response)
{
//After successfully Creating user
authenticateUserAndSetSession(user, request);

return "redirect:/home/";
}

private void authenticateUserAndSetSession(User user,
HttpServletRequest request)
{
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
user.getUsername(), user.getPassword());

// generate session if one doesn't exist
request.getSession();

token.setDetails(new WebAuthenticationDetails(request));
Authentication authenticatedUser = authenticationManager.authenticate(token);

SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
}

}

最佳答案

首先,为您的 AuthenticationManager 提供明确的 bean 名称

<authentication-manager alias="authenticationManager">
...
</authentication-manager>

其次, Autowiring 时使用限定符:

@Autowired
@Qualifier("authenticationManager")
protected AuthenticationManager authenticationManager;

关于spring - 手动获取 AuthenticationManager 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5417509/

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