@Autowired
@Qualifier("org.springframework.security.authenticationManager")
protected AuthenticationManager authenticationManager;
@RequestMapping(value = "/test")
public ModelAndView test(HttpServletRequest request,HttpServletResponse response){
//跳轉首頁
ModelAndView view = new ModelAndView("pages/index");
//使用用戶名、密碼生成可用AuthenticationToken(用戶名:test,密碼:123456)
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("test", "123456");
//設置authenticationToken的details,主要獲取請求信息
authenticationToken.setDetails(new WebAuthenticationDetails(request));
//使用authenticationManager接口中的anthenticate進行springsecurity認證
Authentication authenticatedUser = authenticationManager.authenticate(authenticationToken);
//將認證信息放入安全上下文中(此處為個人理解)
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
//如果沒有session,生成一個session並設置當前的securityContext
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
//此sessionId為響應給瀏覽器的jsessionId(可在瀏覽器中查看cookie中的jsessionId與此值是否相等)
String sessionId = request.getSession().getId();
System.out.println(jsessionId);
return view;
}