JWT

定义

JWT全称(json WEB token),是基于json数据结构的数据验证⽅方式,其本质是对json数据进行加密后产⽣生的字符串

使用场景

解决session使用

JWT交互过程

JWT交互过程.png
传统单体式与分布式/集群区别.png

使用

/*服务端生成token*/
public class TestServlet extends javax.servlet.http.HttpServlet {

    public static final String key = "XAJSANJHABSLANSJKAHNAJNSAJHSJ1212";

    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        response.setContentType("application/json;charset=utf-8");

        if (name.equals("jerry") && pwd.equals("123")){
            //生成一个Token 返回客户端
            JWTCreator.Builder builder = JWT.create();
            //指定签名算法 ,传入一个秘钥
            Algorithm algorithm = Algorithm.HMAC256(key);
            //支持链式调用
            String token = builder
                    .withSubject("test jwt")//主题
                    .withExpiresAt(new Date(new Date().getTime() + (1000 * 60 * 30)))//设置有效时间
                    .withClaim("userid", "abcdefg")//负载数据(自定义的数据)
                    .sign(algorithm);//指定算法
            System.out.println("token:"+token);

            //将token放入响应头中
            response.setHeader("token",token);

            response.getWriter().print("{\"msg\":\"登录成功\"}");
        }else {
            response.getWriter().print("{\"msg\":\"登录失败\"}");
        }
    }
}

/*验证*/
@WebServlet(name = "CheckServlet",urlPatterns = "/check")
public class CheckServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        //取出token
        String token = request.getHeader("token");
        if (token != null){
            //验证token是否有效,主要看是否过期,以及是否被篡改
            //注意必须使用相同的秘钥
            Algorithm algorithm = Algorithm.HMAC256(TestServlet.key);
            JWTVerifier verifier = JWT.require(algorithm).build();
            try{
                verifier.verify(token);
                //验证成功 从token中获取用户的信息
                DecodedJWT decode = JWT.decode(token);
                String userid = decode.getClaim("userid").asString();
                System.out.println("用户身份标识:"+userid);
                response.getWriter().print("{\"msg\":\"token验证成功 欢迎使用\"}");

            }catch (JWTVerificationException e){
                response.getWriter().print("{\"msg\":\"token验证失败\"}");
            }
        }else{
            response.getWriter().print("{\"msg\":\"缺少token\"}");
        }
    }
}

你可能感兴趣的:(JWT)