JWT. NET's use

Source: Internet
Author: User
Tags hmac

What is a JWT?

The full name of the JWT is the JSON Web Token, a concise, URL-safe declarative specification for communicating security information between the 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.

The structure of the JWT

JWT is generally composed of three paragraphs, separated by a. Number, the first paragraph is the header, the second is payload, and the third is signature, for example:

Eyj0exaioijkv1qilcjhbgcioijiuzi1nij9.eyjuyw1lijoitxjcdwcilcjlehaioje1mti5ntkzmdmumcwianrpijoibhvvemhpcgvuzyj9.9iwgmhms0mo Phyfglilk15hs_ee770ichaz-bwcx5c0

1. Header

JWT's head carries two pieces of information:

The claim type. This is JWT.
The algorithm that declares the encryption. HMAC SHA256 are usually used directly, and others are RS256, etc.

The full head is like this JSON:

{    "alg": "HS256",    "Typ": "JWT"}

The head is then base64 encrypted (the encryption can be decrypted symmetrically), forming the first part

Eyj0exaioijkv1qilcjhbgcioijiuzi1nij9

2, Playload

Loads are places where effective information is stored. The name is like the cargo on the plane, which contains three pieces of information:

Declaration of registration in the standard
Public statements
Private claims

Declarations registered in the standard (recommended but not mandatory):

ISS:JWT issued by
SUB:JWT-oriented users
AUD: The party receiving the JWT
EXP:JWT expiration time must be greater than the time of issue
NBF: Defines the time before which the JWT is not available.
IAT:JWT Time of issue
JTI:JWT's unique identity is used primarily as a one-time token to avoid replay attacks.

Public statements:
Public declarations can add any information, generally add information about the user or other necessary information for business needs. However, it is not recommended to add sensitive information because the part is decrypted on the client.

Private statement:
A private statement is a statement that is defined by both the provider and the consumer, and is generally not recommended for storing sensitive information, because Base64 is symmetric and decrypted, meaning that the part of the information can be classified as plaintext information.

Define a Playload

{    "name": "Mrbug",    "exp": 1512959303,    "JTI": "Luozhipeng"}

It is then base64 encrypted to get the second part of the JWT

Eyjuyw1lijoitxjcdwcilcjlehaioje1mti5ntkzmdmumcwianrpijoibhvvemhpcgvuzyj9

3, Signature

The third part of JWT is a visa information, which consists of three parts:

Header (after Base64)
Payload (after Base64)
Secret

This section requires Base64 encrypted headers and Base64 after the encrypted payload is used. A string consisting of a connection and then a combination of encryption by adding secret through the encryption declared in the header, then constitutes the third part of the JWT.

// JavaScript var encodedstring = Base64urlencode (header) + '. ' + Base64urlencode (payload); var // 9iwgmhms0mophyfglilk15hs_ee770ichaz-bwcx5c0

Use these three parts. Connect to a complete string that forms the final JWT:

Eyj0exaioijkv1qilcjhbgcioijiuzi1nij9.eyjuyw1lijoitxjcdwcilcjlehaioje1mti5ntkzmdmumcwianrpijoibhvvemhpcgvuzyj9.9iwgmhms0mo Phyfglilk15hs_ee770ichaz-bwcx5c0


Note: The secret is stored on the server side, and the JWT sign-up is also on the server side, secret is used for the signing of JWT and JWT verification, so it is your service side of the private key, in any scenario should not be revealed. Once the client learns about this secret, it means that the client can self-issue the JWT.

How to apply

Usually add authorization in the request head and add bearer callout:

Fetch ('api/user/1', {  headers: {    'Authorization ' '  ' + Token  }})

The server verifies the token and returns the appropriate resource if the validation is passed. The whole process is this:


Safety-related

You should not store sensitive information in the payload portion of the JWT, because that part is the part that the client can decrypt.

Protect the secret private key, which is very important.

If possible, use the HTTPS protocol

How to use in. Net

This is to use a jwt.net third-party library, can be obtained by NuGet, currently the latest version is 3.1.1, the most new version only supports. NET framework4.6 and above,

Because, I am using. NET framework4.5 in my project, so I installed Jwt.net 3.0.0, you can use the VS Tool/NuGet Package Manager/Package Manager console, enter the following command to install manually

Install-package Jwt-version 3.0.0

1, create tokens, here, we only need to customize the payload and Secrect keys, you can generate a three-paragraph format of the string

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>{        { "name","Mrbug" },                        {"Exp", secondssinceepoch+ - },        {"JTI","Luozhipeng" }}; Console.WriteLine (Secondssinceepoch); 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

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);//token is the String Console.WriteLine (JSON) that was previously generated;}Catch(tokenexpiredexception) {Console.WriteLine ("Token has expired");}Catch(signatureverificationexception) {Console.WriteLine ("Token has invalid signature");}

3, custom JSON parser, as long as inherit 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

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

4. Custom JSON serialization

The default JSON serialization is done by Jsonnetserializer and can be customized for serialization:

Jsonserializer Customjsonserializer =Newjsonserializer{//All json keys start with lowercase characters instead of the exact casing of the model/property. e.gContractresolver =Newcamelcasepropertynamescontractresolver (),//Nice and easy to read, but can also does formatting.none to reduce the payload size (by hardly anything ...)formatting =formatting.indented,//The best date/time format/standard.Dateformathandling =Dateformathandling.isodateformat,//Don ' t add key/values when the value is null.Nullvaluehandling =Nullvaluehandling.ignore,//Use the enum String-value, not the implicit int value, e.g. "Oolor": "Red"Converters.add (Newstringenumconverter ())};ijsonserializer serializer=NewJsonnetserializer (Customjsonserializer);

Organized from:

Https://github.com/jwt-dotnet/jwt

Http://www.jianshu.com/p/576dbf44b2ae

JWT. NET use of

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.