A detailed explanation of the principle of implementing JSON WEB tokens

Source: Internet
Author: User
Tags sha1 encryption
This paper mainly introduces the implementation principle of JSON WEB tokens. Have a good reference value, follow the small series together to see it

Objective

Recently in the transformation of a Python project, the Python project was reconstructed into a Java project, the process encountered this knowledge point, think this is very practical, so after work back to write this summary, hope that the people can learn from the back, less detours.

First, the advantages of the introduction

The JSON Web tokens, called JWT, is a security policy for the rest interface. There are many advantages in itself:

Solve cross-domain problems: This token-based access strategy overcomes the cross-domain problem of cookies.

Server-side stateless can be scaled horizontally, token can be certified, no need to store session.

System decoupling, token carries all the user information, no need to bind a specific authentication scheme, only need to know the encryption method and key can be encrypted and decrypted, in favor of decoupling.

Prevent cross-site scripting attacks, without cookie technology, regardless of the security issues of cross-station requests.

Second, the principle of introduction

The format of the JSON Web tokens, JWT is a base64 encoded sequence of characters, separated by dots, composed of three parts, head header, message body playload and signed sign.

The head header of 1.JWT is in JSON format:

{  "Typ": "JWT",  "ALG": "HS256",  "exp": 1491066992916}

Where Typ is a shorthand for type, which means that the type is a JWT type, and the encryption method declares that HS256,EXP represents the current time.

2.JWT message body Playload

{  "userid": "123456",  "ISS": "CompanyName"}

The specific fields of the message body can be defined and added according to the business needs, and only the key value of the field should be paid attention to when decrypting.

3. Generation of signed sign

Finally, the signature, the signature is generated by the header and Playload respectively using the Base64url code, followed by the '. ' Connect the two encoded string, and then the concatenation of the string together with the key to the HMAC SHA-256 algorithm encryption, and finally again Base64 encoded, this gets the signature sign. Finally, the header and Playload and sign are connected together to create the entire JWT.

Three, the introduction of calibration

The entire JWT structure is composed of header.playload.sign connections, only sign is encrypted with the key, and all the information in the header and Playload can be directly obtained, sign is only to verify the header and Playload information has been tampered with, so JWT Data cannot be protected, but the above features can be well applied to the authentication of permissions.

1. Encryption

For example, to encrypt the authentication is the UserID field, first assemble the JSON header header and the message body Playload in the previous format, Press Header.playload to form a string, and then according to the key and HS256 encryption Header.playload get sign signature, finally get Jwttoken for header.playload.sign, in the HTTP request URL with parameters to the backend service request authentication.

2. Decryption

The backend service verifies that Jwttoken has access to the interface service for decryption authentication, such as verifying the userid of the visitor, first

Use the string to divide the strings by. Number and get the header and Playload and sign respectively. Then the Header.playload assembly with the key and the HAMC SHA-256 algorithm to encrypt and then get a new string and sign to compare, if the same means that the data has not been tampered with, and then remove exp from the head to determine the survival time, if the survival time to return an empty string, Returns the value of the UserID for the duration of the lifetime.

Iv. code Examples

Encryption and decryption of 1.python code

#!/usr/bin/env python# coding:utf-8from itsdangerous import badtimesignature, signatureexpiredfrom itsdangerous Import Timedjsonwebsignatureserializer as serializerapp_secret_key= "SECRET" max_token_age=1800token_generator = Serializer (App_secret_key, Expires_in=max_token_age) def generate_auth_token (userid):  Access_token = Token_ Generator.dumps ({"userid": userid})  return access_tokendef Verify_token (token):  try:    User_auth = Token_ Generator.loads (token)    print type (token_generator)  except signatureexpired as E:    raise e  except Badtimesignature as E:    raise e  return User_auth

2. Encryption and decryption of Java code

Package Api.test.util;import Java.io.unsupportedencodingexception;import Java.security.invalidkeyexception;import Java.security.nosuchalgorithmexception;import Javax.crypto.mac;import Javax.crypto.secretkey;import Javax.crypto.spec.secretkeyspec;import Org.apache.commons.codec.binary.base64;import Org.springframework.beans.factory.annotation.value;import Org.springframework.stereotype.component;import Lombok.extern.slf4j.slf4j;import net.sf.json.jsonobject;/** * JWT plus decryption Implementation * * @author ZHENGSC */@Slf4jpublic class Tokenuti L {private String ISSUER = "CompanyName";//agency private string app_secret_key = "SECRET";//Key Private long Max_token _age = 1800; Survival/** * Generate userid Accesstoken * * @param userid * @return */Public String Generateaccesstoken (string use    RID) {Jsonobject claims = new Jsonobject ();    Claims.put ("ISS", ISSUER);    Claims.put ("userid", UserID);    String Accesstoken = sign (claims, app_secret_key);  return accesstoken; }/** * Decryption program returns USERID *   * @param token * @return */public string Verifytoken (string token) {string userid = "";      try {string[] splitstr = token.split ("\ \");      String headerandclaimsstr = splitstr[0] + "." +splitstr[1];      String verystr = signHmac256 (Headerandclaimsstr, App_secret_key); Verify that the data has been tampered with if (Verystr.equals (splitstr[2])) {String header = new String (Base64.decodebase64 (splitstr[0]), "U        TF-8 ");        Jsonobject head = Jsonobject.fromobject (header);        Long expire = Head.getlong ("exp") * 1000L;        Long currenttime = System.currenttimemillis (); if (currenttime <= expire) {//Verify the validity period of the Accesstoken string claims = new String (Base64.decodebase64 (splitstr[1]), "          UTF-8 ");          Jsonobject claim = Jsonobject.fromobject (claims);        UserID = (String) claim.get ("userid");    }}} catch (Unsupportedencodingexception e) {log.error (E.getmessage (), E);  } return userid;   }/** * Assembly encryption Results JWT returns * * @param claims* @param appsecretkey * @return * * * Private String sign (Jsonobject claims, string appsecretkey) {string HEADERANDC    LAIMSSTR = Getheaderandclaimsstr (claims);    String signed256 = signHmac256 (Headerandclaimsstr, Appsecretkey);  return headerandclaimsstr + "." + signed256;    }/** * Stitching request Header and declaration * * @param claims * @return * * * Private String GETHEADERANDCLAIMSSTR (Jsonobject claims) {    Jsonobject Header = new Jsonobject ();    Header.put ("Alg", "HS256");    Header.put ("Typ", "JWT");    Header.put ("Exp", System.currenttimemillis () + max_token_age * 1000L);    String headerstr = header.tostring ();    String claimsstr = claims.tostring ();        String headerandclaimsstr = base64.encodebase64urlsafestring (Headerstr.getbytes ()) + "."    + base64.encodebase64urlsafestring (claimsstr.getbytes ());  return headerandclaimsstr; }/** * will headerandclaimsstr use SHA1 encryption to get sign * * @param headerandclaimsstr * @param appsecretkey * @return */P Rivate string signHmac256 (string Headerandclaimsstr, String appsecretkey) {secretkey key = new Secretkeyspec (Appsecretkey.getbytes (), "HmacSHA256");    String result = null;      try {Mac Mac;      Mac = Mac.getinstance (Key.getalgorithm ());      Mac.init (key);    result = Base64.encodebase64urlsafestring (Mac.dofinal (Headerandclaimsstr.getbytes ())); } catch (NoSuchAlgorithmException |    InvalidKeyException e) {log.error (E.getmessage (), E);  } return result; }}
Related Article

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.