代码登录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;
}

转载于:https://www.cnblogs.com/yizw/p/10483918.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值