代碼登錄spring security並且獲取jsessionId


@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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM