JSON Web token online learning Notes

Source: Internet
Author: User
Tags base64

JSON Web Token (JWT)-enables System integration with authorized access

This is a third-party system that accesses the Anyreport reporting system using the JWT authorization implementation case, and the Anyreport reporting system exposes the report resource URL for Third-party systems to access,
A third-party system can use the IFRAME,SRC setting to access a report resource for a report link, where the resource URL is similar to a RESTful API that requires a certified system to access it.
The benefit of the JWT is that there is no need to do login authentication on the server side to establish the Session.

JWT Components

The JSON web token, called jwt, is a token URL security method for passing between the two sides of a network communication
JWT transmission content is composed of header header, load payload, signature signature three parts
The header defines the token type, the encryption type, and tells the server that the encryption method used is HmacSHA256 (HS256)

1234 {  "typ":"JWT",  "alg":"HS256"}

Load payload defines some information that needs to be used: the client id, the time the JWT was created, the user id, the load does not need to transmit sensitive information such as passwords, keys, etc., JWT content through HTTP transmission is not secure.

12345 {  "cid": "OA0001",  "iat" : 1482656248798,  "uid": "admin"}

Cid: is a third-party system, because there may be multiple Third-party system access to the reporting system, the report system can be based on CID query key, failure time, etc. to do JWT content Verification.
Iat: the time the JWT was created, and the server side judged whether the JWT was invalidated by the IAT to prevent the link from being acquired by Others.
Uid: user id, The server can be based on the user to query some user-related information, such as some permission information, this case does not use this FIELD.

The signature signature section is a Base64 string encrypted with the key pair header Base64 and payload Base64.
JWT three sections use "." The linked string, the final JWT is: header base64 string + payload base64 string + HmacSHA256 (headerBase64 + "." + payloadBase64) base64 string

1 eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjaWQiOiJPQTAwMDEiLCJpYXQiOjE0ODI2NTcyODQyMjF9.TeJpy936w610Vrrm+c3+RXouCA9k1AX0Bk8qURkYkdo=
JWT Generation Method

JWT is generated by a third-party system, can use the Server-side language, can also be generated using javascript, this is the simplest, the key is saved on the Third-party system server side when the entry page can be the key to js, JS get the key and generate jwt, Here the Third-party system key is consistent with the report system key, each reserving a copy without Transmission.

12345678910111213 function token() {    var base64 = new Base64();//网上寻找一个base64库    var header= ‘{"typ":"JWT","alg":"HS256"}‘;    var headerBase64 = base64.encode(header);//header base64字符串    var date = new Date();    var payload = ‘{"cid" : "OA0001","iat" : 1482656248798,"uid" : "admin"}‘;    var payloadBase64 = base64.encode(payload); //payload base64字符串    var base64Token = headerBase64 + "." + payloadBase64;    var signature = CryptoJS.HmacSHA256(base64Token, "123456"); //使用google的hmac-sha256.js库    var signatureBase64 = base64.hex2b64(signature.toString());    var jwt = base64Token + "." + signatureBase64;    return jwt;}

Generated base64 token as URL request resource, URL also need to do urlencoding encoding

12 //url?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjaWQiOiJPQTAwMDEiLCJpYXQiOjE0ODI2NTcyODQyMjF9.TeJpy936w610Vrrm%2Bc3%2BRXouCA9k1AX0Bk8qURkYkdo%3Durl?jwt=encodeURIComponent(token());
JWT validation

Verification is done on the report system server side, The validation section is relatively simple, the use of Java to resolve the JWT and to do the verification, the first choice of the JWT "." Divided into parts three parts header,payload, signature, use JS the same key as "123456" for encryption, get the encryption results compared to the signature of jwt, if the equality means that the validation passed.

123456789101112131415161718192021222324252627 public static boolean verify(String jwt) {    String[] parts = jwt.split("\\." );    String payload = StringUtils.newStringUtf8(Base64.decodeBase64(parts[1]));    JSONObject json = JSONObject.fromObject(payload);    String clientId = json.getString("cid");    long iatTime = json.getLong("iat");    //验证jwt是否失效    if(System.currentTimeMillis() - iatTime > 3600 * 1000) {        return false;    }    //验证签名 signature    byte[] content = (parts[0] + "." +  parts[1]).getBytes(StandardCharsets.UTF_8);    byte[] signature = Base64.decodeBase64(parts[2]);    try {        return verifySignatureFor("HmacSHA256", "123456", content, signature);    } catch(Exception e) {        throw new RuntimeException(e);    }}public static boolean verifySignatureFor(String algorithm,  String secret, byte[] contentBytes, byte[] signatureBytes) throws Exception {    byte[] secretBytes = secret.getBytes(StandardCharsets.UTF_8);    Mac mac = Mac.getInstance(algorithm);    mac.init(new SecretKeySpec(secretBytes, algorithm));    return MessageDigest.isEqual(mac.doFinal(contentBytes), signatureBytes);}

? 2017 medium Software All rights Reserved.

JSON Web token online learning Notes

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.