Token插件:Auth0和jjwt对比

18 篇文章 2 订阅

依赖包

<!-- jwt工具 auth0 -->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.10.0</version>
        </dependency>
<!-- jwt工具 jjwt -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.2</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>0.11.2</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
            <version>0.11.2</version>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

 

Auto0工具类

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

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: lizz
 * @date: 2020/1/20 09:58
 */
public class Auth0Util {
    /**
     * 引入apollo的配置
     */
    private static String TOKEN_KEY = "54f12048-1f56-45c1-a3f1-2c546bc2bb42";
    /**
     * jwt有效时间
     */
    private static long TOKEN_TIMEOUT = 10* 60 * 1000;

    /**
     * jwt生成方
     */
    private final static String JWT_ISSUER = "lb-fw-gw";

    /**
     * 生成jwt
     *
     * @param header
     * @return
     */
    public static String create(Map<String, Object> header) {
        return create(header, new HashMap<>(0), JWT_ISSUER, TOKEN_TIMEOUT);
    }

    public static String create(Map<String, Object> header, Map<String, String> claims) {
        return create(header, claims, JWT_ISSUER, TOKEN_TIMEOUT);
    }

    public static String create(Map<String, Object> header, long timeout) {
        return create(header, new HashMap<>(0), JWT_ISSUER, timeout);
    }

    /**
     * 生成jwt
     *
     * @param header
     * @param issuer
     * @return
     */
    public static String create(Map<String, Object> header, Map<String, String> claims, String issuer, long timeout) {
        String token;
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_KEY);
            Date date = new Date(System.currentTimeMillis() + timeout);
            JWTCreator.Builder builder = JWT.create()
                    .withHeader(header)
                    .withIssuer(issuer)
                    .withExpiresAt(date);
            for (String key : claims.keySet()) {
                builder.withClaim(key, claims.get(key));
            }
            token = builder.sign(algorithm);
        } catch (JWTVerificationException exception) {
            System.out.println(exception.getMessage());
            return null;
        }
        return token;
    }

    /**
     * 验证jwt
     *
     * @param token
     * @return
     */
    public static DecodedJWT decode(String token) {
        DecodedJWT jwt;
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_KEY);
            JWTVerifier verifier = JWT.require(algorithm)
//                    .withIssuer(JWT_ISSUER)
//                    .acceptLeeway(1)
//                    .acceptExpiresAt(1)
//                    .acceptIssuedAt(1)
//                    .acceptNotBefore(1)
                    .build();
            jwt = verifier.verify(token);
        } catch (JWTVerificationException exception) {
            System.out.println(exception.getMessage());
            return null;
        }
        return jwt;
    }
}

 

jjwt工具类

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: jsonwebtoken工具类
 * @author: lizz
 * @date: 2020/2/25 4:18 下午
 */
public class JsonWebTokenUtil {
    /**
     * jwt密钥 必须大于32个字符
     */
    private static String TOKEN_KEY = "54f12048-1f56-45c1-a3f1-2c546bc2bb42";
    /**
     * jwt有效时间
     */
    private static long TOKEN_TIMEOUT = 60 * 30 * 1000;

    /**
     * jwt生成方
     */
    private final static String JWT_ISSUER = "lb-fw-gw";

    /**
     * 生成jwt
     *
     * @param header
     * @return
     */
    public static String create(Map<String, Object> header) {
        return create(header, new HashMap<>(2), JWT_ISSUER, TOKEN_TIMEOUT);
    }
    public static String create(Map<String, Object> header, Map<String, String> claims) {
        return create(header, claims, JWT_ISSUER, TOKEN_TIMEOUT);
    }

    public static String create(Map<String, Object> header, long timeout) {
        return create(header, new HashMap<>(2), JWT_ISSUER, timeout);
    }

    public static String create(Map<String, Object> header, Map<String, String> claims, long timeout) {
        return create(header, claims, JWT_ISSUER, timeout);
    }

    /**
     * 生成jwt
     *
     * @param header
     * @return
     */
    public static String create(Map<String, Object> header, Map<String, String> claims, String issuer, long timeout) {
        String token;
        try {
            Date date = new Date(System.currentTimeMillis() + timeout);
            SecretKey key = Keys.hmacShaKeyFor(TOKEN_KEY.getBytes());
            token = Jwts.builder()
                    .setHeader(header)
                    .setClaims(claims)
                    .setIssuer(issuer)
                    .setExpiration(date)
                    .signWith(key, SignatureAlgorithm.HS256)
                    .compact();
        } catch (JwtException exception) {
            System.out.println(exception.getMessage());
            return null;
        }
        return token;
    }

    /**
     * 验证jwt
     *
     * @param token
     * @return
     */
    public static Jws<Claims> decode(String token) {
        Jws<Claims> claimsJws;
        try {
            Key key = new SecretKeySpec(TOKEN_KEY.getBytes(), SignatureAlgorithm.HS256.getJcaName());
            claimsJws = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
        } catch (JwtException exception) {
            System.out.println(exception.getMessage());
            return null;
        }
        return claimsJws;
    }
}

单测

package com.lizz.gateway;

import com.lizz.gateway.util.Auth0Util;
import com.lizz.gateway.util.JsonWebTokenUtil;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: jwt插件对比  auth0 and jjwt
 * @author: lizz
 * @date: 2020/10/28 17:47
 */
public class OnceTester {
    private Logger logger = LoggerFactory.getLogger(OnceTester.class);
    private static Map<String, Object> header = new HashMap<String, Object>() {{
        put("auth", "level1");
    }};
    private static Map<String, String> claims = new HashMap<String, String>() {{
        put("user", "xxxs");
    }};

    private static String token;

    @Test
    public void jwtTest() {
        //需要根据当前时间生成jwt,否则解析会失效
        token = JsonWebTokenUtil.create(header, claims);
        auth0Create(10000);
        jjwtCreate(10000);
        auth0Create(100000);
        jjwtCreate(100000);
        auth0Create(1000000);
        jjwtCreate(1000000);
        auth0Decode(10000);
        jjwtDecode(10000);
        auth0Decode(100000);
        jjwtDecode(100000);
        auth0Decode(1000000);
        jjwtDecode(1000000);
    }

    /**
     * 生成jwt
     *
     * @param times 次数
     */
    private void auth0Create(int times) {
        long btime = System.currentTimeMillis();
        for (int i = 1; i <= times; i++) {
            Auth0Util.create(header, claims);
        }
        logger.info("auth0 Create times:{},time:{}", times, System.currentTimeMillis() - btime);
    }

    /**
     * 生成jwt
     *
     * @param times 次数
     */
    private void jjwtCreate(int times) {
        long btime = System.currentTimeMillis();
        for (int i = 1; i <= times; i++) {
            JsonWebTokenUtil.create(header, claims);
        }
        logger.info("jjwt Create times:{},time:{}", times, System.currentTimeMillis() - btime);
    }


    /**
     * 生成jwt
     *
     * @param times 次数
     */
    private void auth0Decode(int times) {
        long btime = System.currentTimeMillis();
        for (int i = 1; i <= times; i++) {
            Auth0Util.decode(token);
        }
        logger.info("auth0 decode times:{},time:{}", times, System.currentTimeMillis() - btime);
    }

    /**
     * 生成jwt
     *
     * @param times 次数
     */
    private void jjwtDecode(int times) {
        long btime = System.currentTimeMillis();
        for (int i = 1; i <= times; i++) {
            JsonWebTokenUtil.decode(token);
        }
        logger.info("jjwt decode times:{},time:{}", times, System.currentTimeMillis() - btime);
    }
}
18:29:52.217 [main] INFO com.lizz.gateway.OnceTester - auth0 Create times:10000,time:1560
18:29:55.294 [main] INFO com.lizz.gateway.OnceTester - jjwt Create times:10000,time:3068
18:29:58.062 [main] INFO com.lizz.gateway.OnceTester - auth0 Create times:100000,time:2768
18:30:11.734 [main] INFO com.lizz.gateway.OnceTester - jjwt Create times:100000,time:13672
18:30:27.485 [main] INFO com.lizz.gateway.OnceTester - auth0 Create times:1000000,time:15751
18:32:38.006 [main] INFO com.lizz.gateway.OnceTester - jjwt Create times:1000000,time:130520
18:32:39.181 [main] INFO com.lizz.gateway.OnceTester - auth0 decode times:10000,time:1175
18:32:43.956 [main] INFO com.lizz.gateway.OnceTester - jjwt decode times:10000,time:4775
18:32:45.932 [main] INFO com.lizz.gateway.OnceTester - auth0 decode times:100000,time:1976
18:33:23.977 [main] INFO com.lizz.gateway.OnceTester - jjwt decode times:100000,time:38045
18:33:38.295 [main] INFO com.lizz.gateway.OnceTester - auth0 decode times:1000000,time:14318
18:40:11.813 [main] INFO com.lizz.gateway.OnceTester - jjwt decode times:1000000,time:393518

 

测试数据

取3次中位数。

操作decodecreate
次数auth0jsonwebokenauth0jsonwebtoken
1,0001665 ms2842 ms23062398 ms
10,0002951 ms9755 ms39525246 ms
100,0005786ms38859 ms1178416191 ms

结论

  • 性能方面auth0更优。
  • 功能方面jsonwebtoken支持更高级的应用,如高级加密算法等。
  • 7
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lizz666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值