zoukankan      html  css  js  c++  java
  • 代码登录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;
    }

  • 相关阅读:
    如何搭建Redis集群
    AOP的作用
    IDEA上传代码到GitGub
    Runnable的作用及使用方式
    idea如何自动生成序列化ID?
    15000 字的 SQL 语句大全
    图解算法时间复杂度
    图解JVM的类加载机制(详细版)
    (转)图解排序算法之归并排序
    图解分布式id生成算法SnowFlake
  • 原文地址:https://www.cnblogs.com/yizw/p/10483918.html
Copyright © 2011-2022 走看看