(GO). NET Operation JWT

Source: Internet
Author: User

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

1.JWT definition

JWT (Json Web Token) is a concise, URL-safe declarative specification for communicating security information between two parties. JWT, as an open standard (RFC 7519), defines a concise, self-contained method for communicating information between two communication parties in the form of a JSON object. Because of the presence of digital signatures, this information is trustworthy, and JWT can be signed using the HMAC algorithm or the public-private key pair of RSA.

Components of the 2.JWT

(1) JWT is generally composed of three paragraphs, separated by a. Number, the first paragraph is the header, the second is payload, the third is signature,

For example:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

具体各部分介绍可查看简书(http://www.jianshu.com/p/576dbf44b2ae)


3.jwt.net use

First, you need to introduce jwt.net, which can be added by NuGet: Install-package jwt-version 2.4.2 (choose the right version yourself)

(1) Create tokens, where we only need to customize the payload and Secrect keys to generate a three-part format string

 
varPayload =Newdictionary<string,Object>{    { "claim1",0 },    { "claim2","Claim2-value" }};varSecret ="gqdstcksx0nhjpouxoyg5mbej1xt0ufiwdvvvbrk"; Ijwtalgorithm algorithm=Newhmacsha256algorithm (); Ijsonserializer Serializer=NewJsonnetserializer (); Ibase64urlencoder Urlencoder=NewJwtbase64urlencoder (); Ijwtencoder encoder=NewJwtencoder (algorithm, serializer, urlencoder);vartoken =Encoder. Encode (payload, secret); Console.WriteLine (token);

(2) Token decryption, you can see the output as {"CLAIM1": 0, "claim2": "Claim2-value"}, you can use json["claim1"],json["claim2" the way to get the values, Here JSON is idictionary<string,object> type

vartoken ="eyj0exaioijkv1qilcjhbgcioijiuzi1nij9.eyjjbgfpbteiojasimnsywltmii6imnsywltmi12ywx1zsj9.8pwbi_htxqi3ugqhq_ RDRNSQRXFL1SR8FBQOS-5KM5S";varSecret ="gqdstcksx0nhjpouxoyg5mbej1xt0ufiwdvvvbrk";Try{Ijsonserializer Serializer=NewJsonnetserializer (); Idatetimeprovider provider=NewUtcdatetimeprovider (); Ijwtvalidator Validator=NewJwtvalidator (serializer, provider); Ibase64urlencoder Urlencoder=NewJwtbase64urlencoder (); Ijwtdecoder Decoder=NewJwtdecoder (Serializer, validator, urlencoder); varJSON = 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) Add the expiration time, the expiration time is after this time JWT does not accept processing, the time valid value is a moment and 1970/1/1 00:00:00 the difference of the number of seconds

The following example is the number of seconds 00:00:00 the current time to 1970/1/1, i.e. the expiration time is the current time. If set to current time + 10 seconds, you can add secondssinceepoch=secondssinceepoch+10

 

Idatetimeprovider Provider =NewUtcdatetimeprovider ();varnow =provider. Getnow (); varUnixepoch =NewDateTime (1970,1,1,0,0,0, DATETIMEKIND.UTC);//or use Jwtvalidator.unixepochvarSecondssinceepoch = Math.Round (now-Unixepoch). TotalSeconds); varPayload =Newdictionary<string,Object>{    { "Exp", Secondssinceepoch}};varSecret ="gqdstcksx0nhjpouxoyg5mbej1xt0ufiwdvvvbrk";vartoken =Encoder. Encode (payload, secret); varJSON = decoder. Decode (token, secret);//tokenexpiredexception

(4) You can also customize the JSON parser as long as you inherit the Ijsonserializer interface

 Public class customjsonserializer:ijsonserializer{    publicstring Serialize (object  obj)    {        //  Implement using favorite JSON serializer    }       public T deserialize<t> (string  json)    {        //  Implement Using favorite JSON Serializer    }}

Use this parser

New NEW Newnew Jwtencoder (algorithm, serializer,  Urlencoder);

(GO). NET Operation JWT

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.