Get instance of AuthenticationManager Manually
I'm trying to implement the below, but my authenticationManager instance throws the below exception and is not autowired. How do I get an instance of it from Spring manually? I'm not using a spring controller, I'm using a JSF request scoped bean. I get the below exception at runtime when the container tries to autowire the authenticationManager. The requestCache comes in fine. I don't understand why I have two instances...
config:
<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 i开发者_StackOverflow社区f one doesn't exist
request.getSession();
token.setDetails(new WebAuthenticationDetails(request));
Authentication authenticatedUser = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
}
}
First, provide an explicit bean name for your AuthenticationManager
<authentication-manager alias="authenticationManager">
...
</authentication-manager>
Second, use qualifier when auto-wiring:
@Autowired
@Qualifier("authenticationManager")
protected AuthenticationManager authenticationManager;
精彩评论