java版jwt实现和dotnet版的jwt实现

38 篇文章 0 订阅

一部分小伙伴用java实现了jwt,但用dotnet如何实现解码和编码呢?

java端实现方式如下

参考了

GitHub - oktadev/okta-java-jwt-example: JSON Web Tokens with Java

 生成token如下:

    private static final String JWT_SECERT = "b9b7b9154fd95mo0";

    private static SecretKey generalKey() {
        byte[] encodeKey = Base64.getDecoder().decode(JWT_SECERT);
        SecretKey key = new SecretKeySpec(encodeKey, 0, encodeKey.length, "AES");
        return key;
    }

    public String createJwt(String userId, Date expiredTimeAt) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        Long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .claim("userId",userId)
                .setExpiration(expiredTimeAt)
                .signWith(signatureAlgorithm, secretKey);
        return builder.compact();
    }

dotnet端 实现

依赖库如下

​​​​​​https://github.com/jwt-dotnet/jwt

using System;
using JWT.Algorithms;
using JWT.Builder;

public class Program
{
	public static void Main()
	{
		var token = JwtBuilder.Create()
			.WithAlgorithm(new HMACSHA256Algorithm())
			.WithSecret("0424abdb9b7b9154fd95mo0")
			.AddClaim("userId", "userId")
			.AddClaim("exp", 65494427999)
		    .Encode();
		Console.WriteLine(token);
		
		var payload = JwtBuilder.Create()
			.WithAlgorithm(new HMACSHA256Algorithm())
			.WithSecret("0424abdb9b7b9154fd95mo0")
			.Decode(token);
		Console.WriteLine(payload);
	}
}

 jwt的阅读工具

jwt.ms: Welcome!

refs:

https://github.com/jwt-dotnet/jwt/issues/404

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值