其他分享
首页 > 其他分享> > zbb20190110 jwt生成token

zbb20190110 jwt生成token

作者:互联网

TokenUtil 
package com.zbb.app.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * token 生成、解析工具类
 */
@Slf4j
public class TokenUtil {
    public static void main(String[] args) {
        String jwtToken = getJWTToken("e3f0e9268f574aa2858d75c7d44ab93a", "cwag");
        System.out.println(jwtToken);
        String accountIdByToken = getAccountIdByToken(jwtToken, "cwag");
        System.out.println(accountIdByToken);
    }

    private TokenUtil() {

    }

    /**
     * 生成Token
     *
     * @param accountId 账户Id
     * @param tokenSalt 加密盐
     * @return token
     */
    public static String getJWTToken(String accountId, String tokenSalt) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        // 生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(tokenSalt);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes,
                SignatureAlgorithm.HS256.getJcaName());
        // 添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .claim("ACCOUNT_ID", accountId).signWith(SignatureAlgorithm.HS256, signingKey);
        // 生成JWT
        return builder.setNotBefore(now).compact();
    }

    /**
     * 解析token值
     *
     * @param jwtToken token值
     * @param tokenSalt 加密盐
     * @return 账户Id
     */
    public static String getAccountIdByToken(String jwtToken, String tokenSalt) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(tokenSalt))
                    .parseClaimsJws(jwtToken).getBody();
            return claims.get("ACCOUNT_ID").toString();
        } catch (Exception ex) {
            log.error("解析token值:" + ex.getMessage());
            return null;
        }
    }

}

 

pom

<!-- JWT -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>

提醒运行报错java.security.NoSuchAlgorithmException HmacSHA256 not available.

buildpath 改成 jdk

 

标签:String,import,tokenSalt,pre,jwtToken,jsonwebtoken,return
来源: https://www.cnblogs.com/super-admin/p/10251487.html