jwt安全验证

jwt:java web token

区别于session存储安全信息,后者是将信息存储到服务器,前者是存到客户端/浏览器

jwt基础认识

可以参考这篇文章:https://www.cnblogs.com/zjutzz/p/5790180.html

jwt怎么用

基于maven工程:

引入pom


      io.jsonwebtoken
      jjwt
      0.6.0
    

java代码

package com.wlt.jwt.util;

import java.security.Key;
import java.util.Date;
import java.util.logging.Logger;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import com.wlt.jwt.model.AudienceEntity;
import com.wlt.jwt.model.User;
import io.jsonwebtoken.*;
import org.apache.commons.logging.LogFactory;
import org.slf4j.LoggerFactory;
import org.junit.Test;

public class JwtHelper {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(JwtHelper.class);

    /**
     * 验证签名
     * 验证通过返回声明对象否则返回null
     * @param jsonWebToken
     * @param base64Security
     * @return
     */
    public static Claims parseJWT(String jsonWebToken, String base64Security){  
        try  
        {
            //通过密钥检验
             Jws jws= Jwts.parser()
                       .setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
                       .parseClaimsJws(jsonWebToken);
            Claims claims = (Claims) jws.getBody();
            Header header = jws.getHeader();
            log.info(header.toString());
            return claims;  
        }catch (SignatureException e) {          //签名异常
            log.info("Invalid JWT signature.");
            log.trace("Invalid JWT signature trace: {}", e);
        } catch (MalformedJwtException e) {         //JWT格式错误
            log.info("Invalid JWT token.");
            log.trace("Invalid JWT token trace: {}", e);
        } catch (ExpiredJwtException e) {         //JWT过期
            log.info("Expired JWT token.");
            log.trace("Expired JWT token trace: {}", e);
        } catch (UnsupportedJwtException e) {        //不支持该JWT
            log.info("Unsupported JWT token.");
            log.trace("Unsupported JWT token trace: {}", e);
        } catch (IllegalArgumentException e) {        //参数错误异常
            log.info("JWT token compact of handler are invalid.");
            log.trace("JWT token compact of handler are invalid trace: {}", e);
        }
        return null;
    }

    /**
     * 生成jwt串,重点关注claims(载荷-payload),这里面是自定义的声明和默认的声明,默认声明后面验证的时候,验证器默认会帮我们验证,自定义的声明需要自己写验证规则
     * @param name
     * @param userId
     * @param role
     * @param audience
     * @param issuer
     * @param TTLMillis
     * @param base64Security 自定义的用来加密的字符串密钥
     * @return
     */
    public static String createJWT(String name, String userId, String role,   
            String audience, String issuer, long TTLMillis, String base64Security)   
    {  
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;  
           
        long nowMillis = System.currentTimeMillis();  
        Date now = new Date(nowMillis);  
           
        //生成签名密钥  
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);  
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //用默认的hs256加密算法
           
          //添加构成JWT的参数  
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                                        .claim("role", role)  //自定义
                                        .claim("unique_name", name)//自定义
                                        .claim("userid", userId)  //自定义
                                        .setIssuer(issuer)  //#非必须。issuer 请求实体,可以是发起请求的用户的信息,也可是jwt的签发者。
                                        .setAudience(audience)  //#非必须。接收该JWT的一方
                                        .signWith(signatureAlgorithm, signingKey);  //signatureAlgorithm加密算法类型 signingKey加密密钥
         //添加Token过期时间  
        if (TTLMillis >= 0) {  
            long expMillis = nowMillis + TTLMillis;  
            Date exp = new Date(expMillis);  
            builder.setExpiration(exp).setNotBefore(now);  
        }  
         //生成JWT
        return builder.compact();  
    }

    /**
     * 测试
     */
    @Test
    public void test(){
        String jwt = createJWT("name","userid","role","audience","issuer",1000000,"security");
        System.out.println(jwt);
        Claims claims = parseJWT(jwt,"security");
        System.out.println(claims.toString());
    }
} 

使用场景

结合到springsecurity或者springmvc里头,只需要再登入成功的时候生成jwt返回前台存储起来,后面每次登入的时候带上该串做安全验证即可




你可能感兴趣的:(jwt)