我有这段代码
UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(email);
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(authentication);
HttpSession session = request.getSession(true);
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
Run Code Online (Sandbox Code Playgroud)
这是在spring security中手动验证用户身份.我的问题是我应该在哪里放置此代码?把它放在服务层强制我将HttpSession对象带到AFAIK不好的服务层.我不确定将认证逻辑放在表示层中有多好.任何有见解的人?
提前致谢.
我在注册后使用以下方法进行编程登录
private void autoLogin(User user,
HttpServletRequest request)
{
GrantedAuthority[] grantedAuthorities = new GrantedAuthority[] { new GrantedAuthorityImpl(
"ROLE_ADMIN") };
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);
}
Run Code Online (Sandbox Code Playgroud)
用户是经过身份验证但总是有ROLE_ANONYMOUS我不知道为什么?有任何想法吗 ?