单点登录cookie跨域解决方案

通过动态写入html,留的后门3个跨越标签<script><style><img>

------------web1-----------------------index.jsp-------------

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
    ================web1==============
  <button id="btn">点击</button>
  <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
  <script>
    $('#btn').click(function(){
            var frame = document.createElement('script');
            frame.src = 'http://127.0.0.1:8081/web2/servlet/Web2Servlet?name=leo&age=30&callback=func';
            $('body').append(frame);
        });
        
        function func(res){
            alert(res.message+res.name+'你已经'+res.age+'岁了');
        }
  </script>

  </body>
</html>

 

-----------------web2----------Web2Servlet.java------------------

package web2;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class Web2Servlet extends HttpServlet {

    /**
         * Constructor of the object.
         */
    public Web2Servlet() {
        super();
    }

    /**
         * Destruction of the servlet. <br>
         */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("==========web2==============");
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        System.out.println("==========name=============="+name);
        System.out.println("==========age=============="+age);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("message", "success");
        map.put("name", "耿明明");
        map.put("age", "19");
        Gson gson = new Gson();
        String json = gson.toJson(map);
        Cookie ck = new Cookie("lastAcceptTime", System.currentTimeMillis()+"");
        // 设置cookie的存活时间,单位:秒
        ck.setMaxAge(500);
        ck.setPath("/");// 与上面的效果一致,让所有访问地址以path开头的servlet共享该cookie,即这种情况浏览器都携带
        response.addCookie(ck);
        // 解决json中文乱码
        response.setContentType("text/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.println(json);
        out.flush();
        out.close();
    }

    /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request, response);
    }

    /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
    public void init() throws ServletException {
        // Put your code here
    }

}
 

 

 

 

  ==========统一认证中心============

package com.wzwsso.cn.web;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wzwsso.cn.pojo.User;
import com.wzwsso.cn.service.UserService;
import com.wzwsso.cn.utils.WzwResultUtil;

/**
 * 
 * @author 微笑
 * @decription 用户认证的controller
 * @date 2018-04-09
 */
@Controller
@RequestMapping(value="/user")
public class UserController {
   
   @Autowired
   private UserService userService;
   
   @Autowired
   private RedisTemplate<String, Object> redisTemplate;
   
   /**
    * 用户授权接口
    * @param request
    * @return WzwResultUtil
    */
   @RequestMapping(value="auth",method=RequestMethod.POST)
   @ResponseBody
   public WzwResultUtil auth(HttpServletRequest request,HttpServletResponse response){
      try {
         String tokenVal = request.getParameter("token");
         //查询是否有用户信息
         Object redisUser = redisTemplate.opsForValue().get(tokenVal);
         if(redisUser==null) {
            return WzwResultUtil.build(-2, "用户登录凭证错误", "用户登录凭证错误");
         }
         //更新缓存的时间
         updateCache(tokenVal,(User)redisUser);
         /** 将token写入客户端游览器  **/
          Cookie clientCookie = new Cookie("wzw_token", tokenVal);
          clientCookie.setMaxAge(60*30);
          clientCookie.setPath("/");
          response.addCookie(clientCookie);
         return WzwResultUtil.buildIsOk("该凭证授权成功!");
      } catch (Exception e) {
         // TODO: handle exception
         e.printStackTrace();
         return WzwResultUtil.buildIsFail(e.getMessage());
      }
   }
   
   /**
    * 用户统一登录接口
    * @param request
    * @return WzwResultUtil
    */
   @RequestMapping(value="login",method=RequestMethod.POST)
   @ResponseBody
   public WzwResultUtil login(HttpServletRequest request,HttpServletResponse response){
      try {
         String sign = "wzw_123";
         String userName = request.getParameter("userName");
         String passWd = request.getParameter("passWd");
         String from = request.getParameter("from");
         
         if(StringUtils.isEmpty(userName)||StringUtils.isEmpty(passWd)){
            return WzwResultUtil.build(-1, "用户名和密码不能为空", null);
         }
         
         User dbUser = userService.findUserByUserName(userName.trim());
         
         if(dbUser==null){
            return WzwResultUtil.build(-2, "用户名或密码错误", null);
         }
         
         if(!dbUser.getPassWd().trim().equals(passWd.trim())){
            return WzwResultUtil.build(-2, "用户名或密码错误", null);
         }else{
            //登录成功
            //需要生成登录成功的凭证token 返回给客户端 同时redis服务器保存用户信息 token作为redis的key 用户基本信息作为对应的value
            //1.token生产规则  MD5(userName+passWd+Sign)
            String key = DigestUtils.md5Hex(dbUser.getUserName()+dbUser.getPassWd()+sign);
            updateCache(key,dbUser);
            /** 将token写入客户端游览器  **/
             Cookie clientCookie = new Cookie("wzw_token", key);
             clientCookie.setMaxAge(60*30);
             clientCookie.setPath("/");
             response.addCookie(clientCookie);
            return WzwResultUtil.buildIsOk(key);//将token返回到客户端程序
         }
      } catch (Exception e) {
         // TODO: handle exception
         e.printStackTrace();
         return WzwResultUtil.buildIsFail(e.getMessage());
      }
   }
   
   /**
    * 设置或者更新缓存  缓存默认保存半个小时
    * @param key
    * @param dbUser
    */
   public void updateCache(String key,User dbUser){
      redisTemplate.opsForValue().set(key, dbUser,60*30,TimeUnit.SECONDS);//设置到缓存 默认半个小时
   }
}

 

==================web1,web2个客户端拦截器,通过httpclient 调用服务端统一登录认证接口

package com.wzwweb2.cn.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wzwweb1.cn.utils.HttpUtil;

/**
 *
 * @author 微笑
 * @description 登录拦截处理
 * @date 2018-04-09
 */
public class LoginInterceptor implements HandlerInterceptor {

   @Override
   public void afterCompletion(HttpServletRequest httpRequest,
                        HttpServletResponse httpResponse, Object arg2, Exception arg3)
         throws Exception {

   }

   @Override
   public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
                     Object arg2, ModelAndView arg3) throws Exception {


   }

   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                      Object object) throws Exception {
      System.out.println("进入了web1拦截器================");
      String urlString = request.getRequestURI();
      //请求的路径
      String contextPath=request.getContextPath();
      String method = request.getMethod();
      System.out.println("==========method:"+method);
      if(urlString.endsWith("login")&&"POST".equals(method)){
         return true;
      }else{
         //如果不是登录方法 那么就要去sso服务器验证是否登录过 没有登录过返回到登录页面 登录过就通过
         String tokenVal = com.wzwweb1.cn.utils.CookiesGetUtil.getCookies("wzw_token", request);
         if(StringUtils.isEmpty(tokenVal)){
//          response.sendRedirect(contextPath + "/index");
            request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request,response);
            return false;
         }

         Map<String,String> params = new HashMap<>();
         params.put("token", tokenVal);

         String result1 = HttpUtil.send("http://127.0.0.1:8081/sso/user/auth",params,"utf-8");
         JSONObject obj = JSON.parseObject(result1);
         if(obj.getInteger("code")==200){
            //登录成功
            //request.getRequestDispatcher("/WEB-INF/jsp/web1Main.jsp").forward(request,response);
            return true;
         }else{
            //
//            response.sendRedirect(contextPath + "/index");
            request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request,response);
            return false;
         }
      }

   }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值