jwt

jwt
基于token后台身份认证
基于jwt的token验证,很不错
利用JWT生成Token

在这里插入图片描述
使用URL发送请求是设置jsessionid时需要注意:jsessionid要大写
在这里插入图片描述

SsoClientInterceptor

package com.sbibits.interceptor;

import com.sbibits.HttpUtil.HttpUtils;
import com.sbibits.HttpUtil.SsoClientUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName SsoClientInterceptor.java
 * @Description TODO
 * @createTime 2019年12月31日 09:06:00
 */
@Component
public class SsoClientInterceptor implements HandlerInterceptor {
    @Override//这个方法return false被拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("登录天猫被拦截");
        //判断用户是否存在会话
        HttpSession session = request.getSession();
        System.out.println("查看session的isLogin=>\t"+session.getAttribute("isLogin"));
        Boolean isLogin = (Boolean) session.getAttribute("isLogin");
        if (isLogin != null && isLogin) {
            return true;
        }
        String token = request.getParameter("token");
        System.out.println("查看token=>\t"+token);
        if (!StringUtils.isEmpty(token)) {
            System.out.println("检测到服务器有token信息");
            //防止伪造,拿到服务器去验证
            //服务器地址                        http://www.sso.com:8080/verify
            String httpUrl = SsoClientUtil.SERVER_URL_PREFIX + "/verify";
            //需要验证的参数
            HashMap<String, String> parmas = new HashMap<>();
            parmas.put("token", token);
            System.out.println("验证token=>\t" + token);
            try {
                String isVerify = HttpUtils.sendHttpRequest(httpUrl, parmas);//http://www.sso.com:8080/verify?token=asdgerbfdthentjjjjj
                System.out.println("isverify值=>\t"+isVerify);
                if ("true".equals(isVerify)) {
                    System.out.println("服务器校验通过");
                    session.setAttribute("isLogin", true);
                    return true;
                }
            } catch (Exception e) {
                System.out.println("服务器校验异常");
                e.printStackTrace();
            }
        } else {
            System.out.println("跳转到登录中心");
            //https://www.tmall.com/login&redirectURL=https://www.tmall.com
            SsoClientUtil.redirectToSSOURL(request, response);//没有会话,tc转到统一认证中心
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {

    }
}

serverController

package com.sbibits.controller;

import com.sbibits.db.MockDB;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName ServerController.java
 * @Description TODO
 * @createTime 2019年12月31日 08:44:00
 */
@Controller
public class ServerController {
    @RequestMapping("index")
    public String login() {
        return "login";
    }

    @RequestMapping("toLogin")
    public String toLogin(String name, String pwd, String redirectUrl, HttpSession session, RedirectAttributes ra,Model model) {
        System.out.println("Debug:name=>" + name + "\tpwd=>" + pwd);
        System.out.println("Debug:redirectUrl=>\t"+redirectUrl);
        //模拟数据库
        if ("张三丰".equals(name) && "aaa".equals(pwd)) {
            //给用户创建一个token
            String token = UUID.randomUUID().toString();
            System.out.println("生成token==>\t" + token);
            //存到数据库
            MockDB.T_TOKEN.add(token);
            System.out.println("查看模拟数据库的大小=>\t"+MockDB.T_TOKEN.size());
            //把token存到session
            session.setAttribute("token", token);//和客户信息没有关系
            //返回到客户端
//            model.addAttribute("token", token);=========================================改了
            redirectUrl=redirectUrl+"?token="+token;
            return "redirect:" + redirectUrl;//从哪来回哪去
        }
        //登录不成功
        System.out.println("用户名密码错误");
        ra.addFlashAttribute("redirectUrl" + redirectUrl);
        return "redirect:/index";
    }

    //检测login
    @GetMapping("checkLogin")
    public String checkLogin(String redirectUrl, HttpSession session, RedirectAttributes ra,Model model) {
        //判断这个用户是否登录,是否拥有token
        String token = (String) session.getAttribute("token");//获取服务器端的session里的token
        if (StringUtils.isEmpty(token)) {//没有
            //不存在全局回话,去登陆页面
            System.out.println("=============中间页=============");
            ra.addFlashAttribute("redirectUrl", redirectUrl);
            return "redirect:/index";
        } else {
            //存在全局回话,返回到来的地方
            model.addAttribute("token", token);
            System.out.println("存在全局token,返回到来的地方=>"+token);              //这块可能没啥用
//            redirectUrl=redirectUrl+"?token="+token;
            return "redirect:" + redirectUrl;
        }
    }

    @RequestMapping("verify")
    @ResponseBody//http://www.sso.com:8080/verify?token=asdgerbfdthentjjjjj
    public String verifyToken(String token) {
        if (MockDB.T_TOKEN.contains(token)) {
            System.out.println("服务器校验通过");
            return "true";
        }
        return "false";
    }
}

package com.sbibits.HttpUtil;

import org.springframework.util.StreamUtils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName HttpUtils.java
 * @Description TODO
 * @createTime 2019年12月31日 07:56:00
 */
public class HttpUtils {
    public static String sendHttpRequest(String httpUrl, Map<String, String> map) throws Exception {
        System.out.println("HttpUtils重定向=>\t验证");
        //定义需要访问的地址
        URL url = new URL(httpUrl);
        //打开连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //请求方式
        connection.setRequestMethod("POST");
        //携带参数
        connection.setDoOutput(true);
        if (map != null && map.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : map.entrySet()) {
                sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
            }
        connection.getOutputStream().write(sb.substring(1).toString().getBytes("UTF-8"));
        }
        //发起请求
        connection.connect();//连接
        //接受返回值
        String s = StreamUtils.copyToString(connection.getInputStream(), Charset.forName("UTF-8"));
        System.out.println(s);
        return s;//返回调用
    }
}

server-url-prefix=http://www.sso.com:8080
client-host-url=http://www.tm.com:8082
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值