在Spring中注入登录用户

时间:2014-06-05 09:58:22

标签: spring spring-security

您好我希望我的用户通过URL登录,这是由spring保护的。 URL将包含用户名和密码。我尝试通过控制器向customAuthenticationManager发送用户名和密码,然后在CustomAuthentication Provider中检查并返回UsernamePasswordAuthenticationToken。当我检查isauthenticated标志时它显示为true但当我尝试访问安全页面时,它会将我重定向到登录页面。我哪里错了?

1 个答案:

答案 0 :(得分:0)

这不是最好的方法,但尝试这个:

public void login(HttpServletRequest request, String userName, String password)
{
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userName, password);

// Authenticate the user
Authentication authentication = authenticationManager.authenticate(authRequest);
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(authentication);

// Create a new session and add the security context.
HttpSession session = request.getSession(true);
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
}
相关问题