Jwt_Net20

VB.NET 2025-08-02

JSON Web令牌(JWT)实现.NET

该库支持生成和解码JSON Web令牌。

安装

最简单的安装方法是通过Nuget。请参阅此处。否则,您可以自己下载和编译。

用法

创建令牌

 var payload = new Dictionary < string , object > ( )
{
    { "claim1" , 0 } ,
    { "claim2" , "claim2-value" }
} ;
var secretKey = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk" ;
string token = JWT . JsonWebToken . Encode ( payload , secretKey , JWT . JwtHashAlgorithm . HS256 ) ;
Console . WriteLine ( token ) ;

输出将是:Eyj0exaioijkv1qilcjhbgcioijiuzi1nij9999.yjjbgfpbteiojasimnsywltmiiiiiiiiiiiiiiiiii6imnsywltmi12ywx1zsj9.8pwbi

验证和解码令牌

 var token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjbGFpbTEiOjAsImNsYWltMiI6ImNsYWltMi12YWx1ZSJ9.8pwBI_HtXqI3UgQHQ_rDRnSQRxFL1SR8fbQoS-5kM5s" ;
var secretKey = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk" ;
try
{
    string jsonPayload = JWT . JsonWebToken . Decode ( token , secretKey ) ;
    Console . WriteLine ( jsonPayload ) ;
}
catch ( JWT . SignatureVerificationException )
{
    Console . WriteLine ( "Invalid token!" ) ;
}

输出将是:

{"claim1":0,"claim2":"claim2-value"}

您还可以将JSON有效载荷直接划分到具有解释器的.NET对象:

 var payload = JWT . JsonWebToken . DecodeToObject ( token , secretKey ) as IDictionary < string , object > ;
Console . WriteLine ( payload [ "claim2" ] ) ;

将输出:

claim2-value

EXP索赔

如JWT RFC中所述,EXP“索赔确定不得接受JWT的到期时间或之后的到期时间。”如果存在EXP索赔,并且在当前时间之前,则令牌将失败验证。 EXP(到期)值必须指定为自1970 UTC以来的秒数。

 var unixEpoch = new DateTime ( 1970 , 1 , 1 , 0 , 0 , 0 , DateTimeKind . Utc ) ;
var now = Math . Round ( ( DateTime . UtcNow - unixEpoch ) . TotalSeconds ) ;
var payload = new Dictionary < string , object > ( )
{
    { "exp" , now }
} ;
var secretKey = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk" ;
string token = JWT . JsonWebToken . Encode ( payload , secretKey , JWT . JwtHashAlgorithm . HS256 ) ;

string jsonPayload = JWT . JsonWebToken . Decode ( token , secretKey ) ; // JWT.SignatureVerificationException!

配置JSON序列化

默认情况下,JSON序列化由System.Web.Script.Serialization.javaScriptSerializer完成。要配置不同的一个,首先实现了ijsonserializer界面。

 public class CustomJsonSerializer : IJsonSerializer
{
    public string Serialize ( object obj )
    {
        // Implement using favorite JSON Serializer
    }

    public T Deserialize < T > ( string json )
    {
        // Implement using favorite JSON Serializer
    }
}

接下来,将此序列化器配置为jsonserialializer。

 JsonWebToken . JsonSerializer = new CustomJsonSerializer ( ) ;
下载源码

通过命令行克隆项目:

git clone https://github.com/ststeiger/Jwt_Net20.git