1
头图
I am doing single sign-on this week. This time, the single sign-on parsing user information is to parse user information in JWT, but the method of parsing token provided by a third-party document that parses user information from JWT cannot be solved. My mentality at the time It was a bit collapsed. Later I checked some information and found that the third party's way of parsing user information from JWT was problematic, but I still didn't know much about JWT, so I planned to learn JWT systematically.

JWT overview

What is it?

I generally like to learn new technology because the official documents are concise and clear. JWT is that the official website of JWT is very good. At first glance, what you want to know is right in front of your eyes:
JWT is JSON (If you don’t know what JSON is, you can read the article I wrote before: JSON that is stupid not clear?) The abbreviation of WEB Token (token), so we can literally understand JWT as WEB A token in the form of JSON. You can understand this token as a pass, a token to enter the system.

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.

JWT is a (compact and self-contained) method (or method) defined by the open specification RFC-7519 to use JSON to securely transmit data between different security entities.

his information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

Because JWT is digitally signed, the information transmitted using JWT can be verified and trusted. Electronic signatures can be implemented using the HMAC algorithm or the public and private keys of RSA and ECDSA asymmetric encryption.

Although JWTs can be encrypted to also provide secrecy between parties, we will focus on signed tokens. Signed tokens can verify the integrity of the claims contained within it, while encrypted tokens hide those claims from other parties. When tokens are signed using public/private key pairs, the signature also certifies that only the party holding the private key is the one that signed it.
Although JWT is encrypted to provide security for the exchange of information between two secure entities, we still focus on the signed token. The signed token (or signed token) can verify the integrity of the information contained in it. The encrypted token also hides the source's information. When the signature method used by the token holds the public key or the private key, the signature can also verify that the party holding the private key is the party who signed the token.

What is RFC?

RFC is the abbreviation of Request for Comments. The translation can be understood as a draft for comments. There are a series of standards and protocols on the Internet, such as HTTP, TCP, etc. Who will advance or update these protocols and standards? It is promoted and updated by the Internet Engineering Task Force (IETF). The RFC is like a draft for comments. Every network protocol update will have a corresponding RFC, which will be implemented after being reviewed and approved by the IETF. In March 1996, Tsinghua University submitted a unified transmission standard for Chinese characters adapted to Chinese encodings in different countries and regions. It was adopted by the IETF as RFC 1922, becoming the first submission protocol recognized as an RFC document in Mainland China.

What can it be used for?

  • Authorization: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.

    Authentication: This is the most common use scenario of JWT. As long as the user successfully logs in once, and each subsequent request carries the JWT, he can access everything that the JWT is allowed to access (we can understand that JWT is similar to an ID card Existence, the server can know who the currently logged-in user is and the resources that are allowed to access by getting the JWT from the request). Nowadays, single sign-on is widely implemented using JWT because of its low overhead and its ability to be used in easily different security entities.
  • Information Exchange: JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed—for example, using public/private key pairs—you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't been tampered with.
Information exchange: JWT is a good implementation for the secure exchange of information between different entities. Because of the JWT signature, such as using asymmetric encryption, you can be sure of the sender’s identity (to prevent third-party impersonation). The signature is passed through the JWT header and The payload is calculated. You can use this to verify whether the information has been modified

Composition of JWT

header

For the time being, this payload can be understood as the request body, which carries the information to be exchanged. The information carried in the header is encrypted, and it is also encrypted with Base64URL. The three parts of JWT are divided by ., a typical JWT composition is as follows:

xxxxx.yyyyy.zzzzz

Typical header composition:

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

claims

The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.
Payload carries the exchanged information. The exchanged information is in the statement. The information exchanged is generally the entity (typically the user) and some additional data. There are three types of statements:

  • Registered claims: These are a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims. Some of them are: iss (issuer), exp (expiration time), sub (subject), aud (audience), and others.

    These declarations are pre-defined fields that are not mandatory but recommended, and are used to provide a set of valid declarations. Some typical, such as iss (issuer), exp (expiration time), sub (subject body), etc., why are they abbreviations? Because JWT requires compactness.
  • Public claims

    These can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.
    These can be customized by people who use JWTs, but in order to avoid conflicts, register them in the IANA JSON Web Token Registry after the definition, or they can avoid conflicts when they are defined in the URI.
  • Private claims:

    These are the custom claims created to share information between parties that agree on using them and are neither registered or public claims.
    This is a statement that both parties exchange information in a unified manner, and should not be registered or published in a public statement.
    We can understand claims as fields, Registered claims as predefined fields, and Public claims as fields agreed upon by everyone. Payload is also encrypted with Base64.
Do note that for signed tokens this information, though protected against tampering, is readable by anyone. Do not put secret information in the payload or header elements of a JWT unless it is encrypted.
If the information is not encrypted, it is not recommended to put confidential information in the payload. Although this information can be protected by a signature and cannot be tampered with, anyone can read it.
Example payload:
{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

signature

To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that .For example if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:
To create the signature part, you need to encode the header, payload, and secret according to the encryption algorithm in the request header. The following is a typical example of creating a signature using the HMAC SHA256 algorithm:

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

The signature is used to verify the message wasn't changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.

The function of this signature is to verify whether the information has been changed during the transmission process. In the case of using the private key signature, we can verify the identity of the sender.

how to use?

Let's try to use JWT now. First, we go to the maven private server and find the corresponding jar package:

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.18.1</version>
</dependency>

Generate JWT and parse JWT

public class Test {
    public static void main(String[] args) {
        String  str = makeToken();
        parseToken(str);
    }

    private static void parseToken(String str) {
        // 放入签发的密钥,对JWT进行解密
        Jwt info = Jwts.parser().setSigningKey("changanbujian").parse(str);
        System.out.println(info);
    }

    private static String makeToken() {
        Map<String,Object> header = new HashMap<>();
        header.put("alg","HS256");
        header.put("typ","JWT");
        Claims claims = new DefaultClaims();
        claims.setId("ccc").setSubject("aaa").setIssuer("bbb").setExpiration(new Date(System.currentTimeMillis() + 1800 * 1000));
        String secret = "changanbujian";
        // 上面讲过JWT需要Base64的形式
        byte[] saltBase64 = DatatypeConverter.parseBase64Binary(secret);
        SignatureAlgorithm hs256 = SignatureAlgorithm.HS256;
        SecretKeySpec secretKeySpec = new SecretKeySpec(saltBase64,hs256.getJcaName());
        String jwtToken = Jwts.builder().setHeader(header).setClaims(claims).signWith(hs256, secretKeySpec).compact();
        return jwtToken;
    }
}

in conclusion

JWT is the abbreviation of JSON WEB TOKEN. It is a form of token and consists of three parts:

  • header

    Carrying encryption algorithm
  • payload

    Carry information
  • signature

    Generated according to header and payload to prevent tampering and confirm the identity of the sender.

In actual use, we often encrypt information on the basis of the original JWT. Only when the encryption and decryption methods are correct, can the information be parsed from the ciphertext.

Reference

  • JWT document translation Chinese-English - introduction
  • JWT official website

北冥有只鱼
147 声望36 粉丝