手动获取AuthenticationManager的实例

时间:2011-03-24 10:07:51

标签: spring spring-security

我正在尝试实现以下内容,但我的authenticationManager实例抛出以下异常并且未自动装配。如何手动从Spring获取它的实例?我没有使用弹簧控制器,我正在使用JSF请求范围的bean。当容器尝试自动装配authenticationManager时,我在运行时得到以下异常。 requestCache很好。我不明白为什么我有两个实例...

配置:

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

注入自动连接的依赖项失败;嵌套异常是org.springframework.beans.factory.BeanCreationException:无法自动装配字段:protected org.springframework.security.authentication.AuthenticationManager com.dc.web.actions.SignUpDetail.authenticationManager;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有定义类型为[org.springframework.security.authentication.AuthenticationManager]的唯一bean:期望的单个匹配bean但找到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);
    }

}

1 个答案:

答案 0 :(得分:33)

首先,为AuthenticationManager

提供一个明确的bean名称
<authentication-manager alias="authenticationManager">
   ...
</authentication-manager>

其次,在自动布线时使用限定符:

@Autowired
@Qualifier("authenticationManager")
protected AuthenticationManager authenticationManager;
相关问题