jwt_token的生成与解密

关键代码生成
jwt_token的生成与解密_第1张图片

认证token的合法性
jwt_token的生成与解密_第2张图片

 认证token的合法性扩展

import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.Verification;
import com.auth0.jwt.interfaces.DecodedJWT;

void verifyJWTToken(JWTToken token, JWTPrincipal principal) {
	try {
		Algorithm algorithm = Algorithm.HMAC256(principal.getSecret());
		Verification verification = JWT.require(algorithm);
		verification.withSubject(principal.getSubject());
		if (!principal.getRoles().isEmpty()) {
			verification.withArrayClaim("roles", principal.getRoles().toArray(new String[0]));
		}
		withClaims(verification, principal);
		verification.build().verify(token.getToken());
	} catch (UnsupportedEncodingException | JWTVerificationException e) {
		throw new AuthenticationException("invalid user credential info", e);
	}
}

protected void withClaims(Verification verification, JWTPrincipal principal) {
	boolean loginWithWx = ((UserPrincipal) principal).isLoginWithWx();
	verification.withClaim("loginWithWx", loginWithWx);
}

JWT的解码获得信息 

import com.auth0.jwt.interfaces.DecodedJWT;
DecodedJWT decodeToken=JWT.decode(token);
decodeToken.getSubject();
decodeToken.getExpiresAt();
decodeToken.getClaim("loginWithWx").asBoolean();
decodeToken.getClaim("roles").asList(String.class).stream().forEach(record ->{
	System.out.println("----roles="+record);
});

代码部分
pom.xml 


    com.auth0
    java-jwt
    3.1.0

加密类 


import java.io.UnsupportedEncodingException;
import java.util.Date;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;

/**
 * 加密
 * @author 张超
 *
 */
public final class Encrypt {

    /**
     * 生成加密后的token
     * @param isVip 是不是VIP,true表示是VIP,false表示不是VIP。
     * @param username 用户名
     * @param name  姓名
     * @return 加密后的token
     */
    public String getToken(final boolean isVip, final String username,
            final String name) {
        String token = null;
        try {
            Date expiresAt = new Date(System.currentTimeMillis() + 24L * 60L * 3600L * 1000L);
            token = JWT.create()
                .withIssuer("auth0")
                .withClaim("isVip", isVip)
                .withClaim("username", username)
                .withClaim("name", name)
                .withExpiresAt(expiresAt)
                // 使用了HMAC256加密算法。
                // mysecret是用来加密数字签名的密钥。
                .sign(Algorithm.HMAC256("mysecret"));
        } catch (JWTCreationException exception){
            //Invalid Signing configuration / Couldn't convert Claims.
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return token;
    }
}

解密类 
 

import java.io.UnsupportedEncodingException;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

/**
 * 解密
 * @author 张超
 *
 */
public final class Decrypt {

    /**
     * 先验证token是否被伪造,然后解码token。
     * @param token 字符串token
     * @return 解密后的DecodedJWT对象,可以读取token中的数据。
     */
    public DecodedJWT deToken(final String token) {
        DecodedJWT jwt = null;
        try {
            // 使用了HMAC256加密算法。
            // mysecret是用来加密数字签名的密钥。
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256("mysecret"))
                .withIssuer("auth0")
                .build(); //Reusable verifier instance
            jwt = verifier.verify(token);
        } catch (JWTVerificationException exception){
            //Invalid signature/claims
            exception.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jwt;
    }
}

使用
 

package com.qbsea.jwtz;

import com.auth0.jwt.interfaces.DecodedJWT;

public class Main {

    public static void main(String[] args) {
        // 生成token
        Encrypt encrypt = new Encrypt();
        String token = encrypt.getToken(true, "zhangchao", "张超");
        // 打印token
        System.out.println("token: " + token);
        // 解密token
        Decrypt decrypt = new Decrypt();
        DecodedJWT jwt = decrypt.deToken(token);
        System.out.println("issuer: " + jwt.getIssuer());
        System.out.println("isVip:  " + jwt.getClaim("isVip").asBoolean());
        System.out.println("username: " + jwt.getClaim("username").asString());
        System.out.println("name:     " + jwt.getClaim("name").asString());
        System.out.println("过期时间:      " + jwt.getExpiresAt());
    }
}

 

你可能感兴趣的:(jwt_token的生成与解密)