JWT (JSON Web Token) : About Jwt.net

Source: Internet
Author: User
Keywords net core jwt jwt json web token
Tags base64 decrypt hmac

1.Concept of 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.


2.Structure of  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.


The header (JWT's head) carries two pieces of information like JSON:
The claim type. This is JWT.
The algorithm that declares the encryption. HMAC SHA256 are usually used directly, and others are RS256, etc.


Playload load is the place where valid 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. But it is not recommended to add sensitive information because that part can be 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, meaning that part of the information can be classified as plaintext information


Define a Playload

The third part of Signature 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 by the encryption declared in the header, which then forms the third part of the JWT


How to apply
Usually add authorization in the request head and add bearer callout:

技术分享图片

In the project's Package Manager console, enter the following:
Install-package Jwt-version 3.0.0
Installing Jwt.net 3.0.0


Static void Main(string[] args)
        {
            IDateTimeProvider provider = new UtcDateTimeProvider();

            Var now = provider.GetNow();

            Var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            Var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);
            Var payload = new Dictionary<string, object>{
               { "name", "MrBug" },
               {"exp",secondsSinceEpoch+100 },
               {"jti","luozhipeng" }
            };

            Console.WriteLine(secondsSinceEpoch);

            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

            String secret = "123";//key
            Var token = encoder.Encode(payload, secret);
            Console.WriteLine(token);

            Decrypt(token,secret);


            Console.ReadKey();

        }

        /// <summary>
        /// decrypt
        /// </summary>
        /// <param name="token">token information</param>
        /// <param name="secret">key</param>
        Private static void Decrypt(string token,string secret)
        {
            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); //token is the previously generated string
                Console.WriteLine(json);
            }
            Catch (TokenExpiredException)
            {
                Console.WriteLine("Token has expired");
            }
            Catch (SignatureVerificationException)
            {
                Console.WriteLine("Token has invalid signature");
            }
        }

About Jwt.net

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.