无需用户名/密码即可进行程序化登录?

时间:2010-11-08 16:35:15

标签: spring-mvc spring-security

祝福所有人 我使用以下方法为用户进行程序化登录,但使用他的用户名和&密码,它工作正常:

public static void autoLogin(User user, HttpServletRequest request,
   AuthenticationManager authenticationManager) {

  GrantedAuthority[] grantedAuthorities = new GrantedAuthority[] { new GrantedAuthorityImpl(
    user.getAuthority()) };

  UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
    user.getUserName(), user.getPassword(),
    grantedAuthorities);

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

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

  SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
  // setting role to the session
  request
    .getSession()
    .setAttribute(
      HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
      SecurityContextHolder.getContext());

 }

我想知道是否可以进行程序化登录但没有用户名或密码验证,只需对此用户进行身份验证。

2 个答案:

答案 0 :(得分:1)

您可以创建自己的Authentication子类,实现支持它的AuthenticationProvider并配置身份验证管理器以使用此提供程序。

(实际上,您只需将Authenticationtrue始终返回isAuthenticated(),但这种方法会绕过SecurityContext,因此,例如,AuthenticationManager将不会被发布。

答案 1 :(得分:0)

设法通过删除这些行来实现

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