JWT前后端分离验证

2018-07-18  本文已影响0人  Selv

2018/07/18

首先是pom文件

      <!--JWT-->
        <!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk16</artifactId>
            <version>1.46</version>
        </dependency>

然后是JwtToken代码

    public static String sercetKey="Jayne";
    public final static long  keeptime=1800000;


    public static String generToken(String id, String issuer, String subject){
        long ttlMillis=keeptime;
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(sercetKey);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        JwtBuilder builder = Jwts.builder().setId(id)
                .setIssuedAt(now);
        if(subject!=null){
            builder.setSubject(subject);
        }
        if(issuer!=null){
            builder.setIssuer(issuer);
        }
        builder .signWith(signatureAlgorithm, signingKey);

        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }


    public static Claims verifyToken(String token){
        Claims claims = Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(sercetKey))
                .parseClaimsJws(token).getBody();
        return  claims;
    }

拦截器验证

  拦截器继承HandlerInterceptor接口
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
            //获取请求的RUi:去除http:localhost:8080这部分剩下的
            String uri = request.getRequestURI();
            //UTL:除了login.jsp是可以公开访问的,其他的URL都进行拦截控制
            if (uri.indexOf("/api/vrc/login") >= 0) {
                return true;
            }

            //验证是否传入Token
            Map map = JedisUtils.getObjectMap("token");
            String WebToken = request.getParameter("token");
            if (WebToken==null){
                JSONObject json=new JSONObject();
                request.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;charset=utf-8");
                json.put("status", "false");
                json.put("msg", "请传入Token");

                response.getWriter().write(json.toString());

                return false;
            }
            //验证Token和userId是否匹配
            Claims WebclaimsToken = JwtToken.verifyToken(WebToken);
            String WebtokenId = WebclaimsToken.getId();

            String WebUserId = request.getParameter("userId");
            String WebUserid = request.getParameter("userid");
            if (!WebUserId.equals(WebtokenId)||WebUserid.equals(WebtokenId)){
                JSONObject json=new JSONObject();
                request.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;charset=utf-8");
                json.put("status", "false");
                json.put("msg", "Token与userId不匹配");

                response.getWriter().write(json.toString());

                return false;
            }
            //登陆验证
            if (map==null){
                JSONObject json=new JSONObject();
                request.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;charset=utf-8");
                json.put("status", "false");
                json.put("msg", "请先登录");

                response.getWriter().write(json.toString());

                return false;
            }else{
                Claims claimsToken = JwtToken.verifyToken((String) map.get("token"));
                String tokenId = claimsToken.getId();
                String userId = (String) map.get("userId");
                if (tokenId.equals(userId)&&WebtokenId.equals(WebUserId)) {
                    return true;
                }
            }
            //不符合条件的给出提示信息,并转发到登录页面
            request.setAttribute("msg", "您还没有登录,请先登录!");
            return false;
        }

        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

        }

        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

        }

代码大部分是网络获取,用

上一篇下一篇

猜你喜欢

热点阅读