JWT.net 操作实践方法
1.JWT定义
JWT(Json Web Token)是一种用于双方之间传递安全信息的简洁的、URL安全的表述性声明规范。JWT作为一个开放的标准( RFC 7519 ),定义了一种简洁的,自包含的方法用于通信双方之间以Json对象的形式安全的传递信息。因为数字签名的存在,这些信息是可信的,JWT可以使用HMAC算法或者是RSA的公私秘钥对进行签名。
2.JWT的组成部分
(1)JWT一般由三段构成,用.号分隔开,第一段是header,第二段是payload,第三段是signature,
例如:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
3.Jwt.Net 使用
首先,需要先引入Jwt.Net,可通过nuget的方式添加:Install-Package JWT -Version 2.4.2(自己选择合适的版本)
(1)创建token,此处,我们只需要自定义payload和secrect密钥即可,可生成三段格式的字符串
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>类型token解密,可看到输出为{ "claim1": 0, "claim2": "claim2-value" },可以用json["claim1"],json["claim2"]的方式获取各个值,此处json为IDictionary<string,object>类型
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
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接口
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 } }
使用该解析器
IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new CustomJsonSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
以上这篇JWT.net 操作实践方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。
您可能感兴趣的文章:
- 基于JWT.NET的使用(详解)