JWT操做(.net)

JWT操做(.net)

 

1.JWT定義html

JWT(Json Web Token)是一種用於雙方之間傳遞安全信息的簡潔的、URL安全的表述性聲明規範。JWT做爲一個開放的標準( RFC 7519 ),定義了一種簡潔的,自包含的方法用於通訊雙方之間以Json對象的形式安全的傳遞信息。由於數字簽名的存在,這些信息是可信的,JWT能夠使用HMAC算法或者是RSA的公私祕鑰對進行簽名。算法

 

2.JWT的組成部分json

(1)JWT通常由三段構成,用.號分隔開,第一段是header,第二段是payload,第三段是signature,安全

例如:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQide

具體各部分介紹可查看簡書(http://www.jianshu.com/p/576dbf44b2ae)post


3.Jwt.Net 使用url

首先,須要先引入Jwt.Net,可經過nuget的方式添加:Install-Package JWT -Version 2.4.2(本身選擇合適的版本)spa

(1)建立token,此處,咱們只須要自定義payload和secrect密鑰便可,可生成三段格式的字符串.net

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var  payload =  new  Dictionary< string object >
{
     "claim1" , 0 },
     "claim2" "claim2-value"  }
};
var  secret =  "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk" ;
 
IJwtAlgorithm algorithm =  new  HMACSHA256Algorithm();
IJsonSerializer serializer =  new  JsonNetSerializer();
IBase64UrlEncoder urlEncoder =  new  JwtBase64UrlEncoder();
IJwtEncoder encoder =  new  JwtEncoder(algorithm, serializer, urlEncoder);
 
var  token = encoder.Encode(payload, secret);
Console.WriteLine(token);

 (2)token解密,可看到輸出爲{ "claim1": 0, "claim2": "claim2-value" },能夠用json["claim1"],json["claim2"]的方式獲取各個值,此處json爲IDictionary<string,object>類型unix

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var  token =  "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjbGFpbTEiOjAsImNsYWltMiI6ImNsYWltMi12YWx1ZSJ9.8pwBI_HtXqI3UgQHQ_rDRnSQRxFL1SR8fbQoS-5kM5s" ;
var  secret =  "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk" ;
try
{
     IJsonSerializer serializer =  new  JsonNetSerializer();
     IDateTimeProvider provider =  new  UtcDateTimeProvider();
     IJwtValidator validator =  new  JwtValidator(serializer, provider);
     IBase64UrlEncoder urlEncoder =  new  JwtBase64UrlEncoder();
     IJwtDecoder decoder =  new  JwtDecoder(serializer, validator, urlEncoder);
     
     var  json = decoder.Decode(token, secret, verify:  true );
     Console.WriteLine(json);
}
catch  (TokenExpiredException)
{
     Console.WriteLine( "Token has expired" );
}
catch  (SignatureVerificationException)
{
     Console.WriteLine( "Token has invalid signature" );
}

 

(3)添加過時時間,過時時間即這個時間以後JWT不接受處理,時間的有效值爲某一時刻和1970/1/1 00:00:00 相差的秒數

下面的例子是當前時間到1970/1/1 00:00:00 的秒數,即過時時間爲當前時間。若是設置爲當前時間+10秒,可添加secondsSinceEpoch=secondsSinceEpoch+10

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
IDateTimeProvider provider =  new  UtcDateTimeProvider();
var  now = provider.GetNow();
 
var  unixEpoch =  new  DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);  // or use JwtValidator.UnixEpoch
var  secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);
 
var  payload =  new  Dictionary< string object >
{
     "exp" , secondsSinceEpoch }
};
var  secret =  "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk" ;
var  token = encoder.Encode(payload, secret);
 
var  json = decoder.Decode(token, secret);  // TokenExpiredException
 
  

 

(4)也可自定義json解析器,只要繼承IJsonSerializer接口

 

1
2
3
4
5
6
7
8
9
10
11
12
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
     }
}

 

使用該解析器

1
2
3
4
IJwtAlgorithm algorithm =  new  HMACSHA256Algorithm();
IJsonSerializer serializer =  new  CustomJsonSerializer();
IBase64UrlEncoder urlEncoder =  new  JwtBase64UrlEncoder();
IJwtEncoder encoder =  new  JwtEncoder(algorithm, serializer, urlEncoder);
相關文章
相關標籤/搜索