Json Web Token (JWT)

Source: Internet
Author: User
Tags base64 compact

JSON Web token (JWT) is a JSON-based open standard (RFC 7519) that executes in order to pass claims across a network application environment. This token is designed to be compact and secure, especially for single sign-on (SSO) scenarios in distributed sites. JWT declarations are typically used to pass authenticated user identities between identity providers and service providers, to obtain resources from a resource server, or to add additional declarative information that is necessary for other business logic, which can also be used directly for authentication or encryption.

Composition

A three-segment base64 string b1.b2.b3 separated by a period, such as: EyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcm9tX3VzZXIiOiJCIiwidGFyZ2V0X3VzZXIiOiJBIn0.rSWamyAYwu Hco7ifagd1orpsp7nzl7bf5t7itqpkvim

    • Header: The header is used to describe the most basic information about the JWT, such as its type and the algorithm used in the signature, in JSON format. Use base64 to turn into a string B1.
    • Paload: Put some custom information in JSON format. Use base64 to turn into a string b2. JWT is pre-placed in five fields:
      • ISS: The issuer of the JWT
      • Sub: The user to which the JWT is intended
      • AUD: The party receiving the JWT
      • EXP (expires): When expires, here is a UNIX timestamp
      • IAT (issued at): when issued
    • Signature: Use the encryption method declared in the header (need to provide a key) to Base64 (header). Base64 (Paload) encryption gets the third base64 string B3.
Calibration principle

Because of the use of Base64, it can be directly reversed code extraction header, payload information. After receiving token, the server will calculate the next signature according to the encryption algorithm declared by the header, if it differs from the signature in token, it is considered as an unauthorized token.

Function

(The difference from a traditional session or token):

    • Suitable for transmitting some non-sensitive information such as UserID, ISAdmin, etc. to the Web application, and cannot contain sensitive information such as passwords;
    • itself has a failure to determine the mechanism: according to the string itself can know whether the token is invalid, and do not have to come out;
    • The server does not need to store tokens, but is distributed to the individual client storage, the session mechanism. There are pros and cons, and JWT adds computational overhead such as decryption, but the overall benefit is greater than the downside.
    • The server can identify the token that has been tampered with, so as long as the token check passes, the information contained in the package can be trusted.
Using the example

Depend on:

        <Dependency>            <groupId>Io.jsonwebtoken</groupId>            <Artifactid>Jjwt</Artifactid>            <version>0.7.0</version>        </Dependency>

Code:

1 ImportJava.security.Key;2 3 ImportIo.jsonwebtoken.Claims;4 Importio.jsonwebtoken.ExpiredJwtException;5 ImportIo.jsonwebtoken.Jws;6 Importio.jsonwebtoken.Jwts;7 Importio.jsonwebtoken.MalformedJwtException;8 ImportIo.jsonwebtoken.SignatureAlgorithm;9 Importio.jsonwebtoken.SignatureException;Ten ImportIo.jsonwebtoken.impl.crypto.MacProvider; One  A  Public classJwttest { -  -      Public Static voidMain (string[] args) { the         //Generate JWT -Key key = Macprovider.generatekey ();//here is the key to encrypt and decrypt.  -String Compactjws = Jwts.builder ()//The returned string is our JWT string. -. Setsubject ("Joe")//Set Theme +. Claim ("StudentID", 2)//Add custom Data -. Signwith (signaturealgorithm.hs512, key)//set Algorithm (required) +. Compact ();//This is the way to spell a JWT string after all settings are complete. ASystem.out.println ("The generated token is:" +Compactjws); at  -         //Resolve JWT -         Try { -  -jws<claims> Parseclaimsjws = Jwts.parser (). Setsigningkey (Key). PARSECLAIMSJWS (COMPACTJWS);//Compactjws for JWT string -Claims BODY = Parseclaimsjws.getbody ();//after we get the body, we can get the information we need from the body. in             //like getting a theme, of course, this is what we've already saved when we generated the JWT string. -String subject =Body.getsubject (); toSystem.out.println ("The subject is:" +subject); +System.out.println ("The StudentID is:" + body.get ("StudentID")); -  the             //OK, we can trust this JWT *  $}Catch(Signatureexception |malformedjwtexception e) {Panax Notoginseng             //Todo:handle Exception -             //don ' t trust the jwt! the             //JWT Parsing Error +}Catch(expiredjwtexception e) { A             //Todo:handle Exception the             //The JWT has expired, and if you set the expiration time when setting up JWT, this will automatically determine if the JWT has expired, and if it expires, we can catch the exception and handle it.  +         } -     } $}
View Code

Resources
    • Json Web token:http://blog.leapoahead.com/2015/09/06/understanding-jwt/
    • Json Web Token Single Sign-on: http://blog.leapoahead.com/2015/09/07/user-authentication-with-jwt/

Json Web Token (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.