一部分小伙伴用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的阅读工具
refs: