祝福所有人 我使用以下方法为用户进行程序化登录,但使用他的用户名和&密码,它工作正常:
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());
}
我想知道是否可以进行程序化登录但没有用户名或密码验证,只需对此用户进行身份验证。
答案 0 :(得分:1)
您可以创建自己的Authentication
子类,实现支持它的AuthenticationProvider
并配置身份验证管理器以使用此提供程序。
(实际上,您只需将Authentication
从true
始终返回isAuthenticated()
,但这种方法会绕过SecurityContext
,因此,例如,AuthenticationManager
将不会被发布。
答案 1 :(得分:0)
设法通过删除这些行来实现
token.setDetails(new WebAuthenticationDetails(request));
Authentication authenticatedUser = authenticationManager .authenticate(token);