What is the JWT

define

JWT, or JSON Web Token, is an open standard (RFC 7519) that defines a compact and self-contained way to securely transfer information between parties as JSON objects. Because this information is digitally signed, it can be verified and trusted. JWT can be signed confidentially (using the HMAC algorithm) or using public/private key pairs of RSA or ECDSA.

Although JWT can be encrypted to provide confidentiality between parties, we will focus on signed tokens. Signed tokens verify the integrity of the claims they contain, while encrypted tokens hide those claims from other parties. When a token is signed using a public/private key pair, the signature also proves that only the party holding the private key is the party signing it.

emmmm……. Balabala a bunch of words, so let’s summarize briefly:

JWT is an open standard for the transmission of JSON information that can be digitally signed using a key to ensure that the information is verifiable and trusted.

structure

JWT consists of three parts: header, payload, and signature. It’s made up of these three parts in a compact form, separated by a dot.

Therefore, JWT is usually shown as follows.

xxxxx.yyyyy.zzzzz

Let’s break down the list of oddities:

header

Headers typically consist of two parts: the type of token (JWT) and the signature algorithm being used, such as HMAC SHA256 or RSA, and so on.

Such as:

{  "alg": "HS256"."typ": "JWT" }
Copy the code

Obviously, this is json data, which is then Base64 encoded to form the first part of JWT, which is XXXXXX in xxXX.yyyyy.zzzzz.

payload

This is the second part of JWT, called the payload. The content is also a JSON object. It is the place to store the valid information.

  • Iss: the issuer of the JWT.
  • Sub: The user that the JWT is aimed at.
  • Aud: The party receiving the JWT.
  • Exp (Expires): When to expire, in this case a Unix timestamp.
  • A: IAT (issued at): when was it issued?

Here’s an example:

{
  "iss": "www.baidu.com"."sub": "you"."aud": "me"."name": "456"."admin": true."iat": 1584091337."exp": 1784091337,}Copy the code

This will also be Base64 encoded and form the second part of JWT, which is yyYYYY in xxXXX.yyyyy. ZZZZZ.

signature

This is the third part of JWT, called the signature, which is used to prevent the JWT content from being tampered with. Use periods for both of the above encoded strings. Join them together (head in front) and they form

xxxxxx.yyyyyy
Copy the code

Then use the signature algorithm declared in the header to sign. To use the HMAC SHA256 algorithm, create a signature in the following ways:

HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
Copy the code

Of course, in the encryption, we also need to provide a secret, we can specify at will. This forms the third part of JWT, which is the ZZZZZZ in xxXXX.yyyyy.zzzzz.

Finally, we put these three parts together to form a complete JWT.

The following shows a complete JWT, which first encodes the header and payload, and finally forms a signature with a key.

If we want to try it out, we can run the debugger on the JWT website. Here’s the official website: jwt.io/

The use of JWT

JWT certification process

When should YOU use JWT

Here are some cases where JSON Web tokens can be useful:

  • Licensing: This is the most common way to use JWT. Once the user is logged in, each subsequent request will include JWT to allow the user to access the routes, services, and resources allowed by the token. Single sign-on is a feature that is widely used in JWT today because it has little overhead and can be easily used across different domains.
  • Information Exchange: JSON Web tokens are a good way to securely transfer information between parties. Because JWT can be signed (for example, using public/private key pairs), you can be sure that the sender is who they say they are. In addition, because the signature is calculated using headers and payloads, you can also verify that the content has been tampered with.

So, someone will say, I know the truth, how should I achieve it? Don’t panic..

Next I will implement JWT authorization and authentication in Python.

In projects where the front and back ends are separated, we need to agree on an identity authentication mechanism with the front end. When a user logs in, the back end generates a token and returns it to the front end. The front end needs to get the token and put it in the header according to certain rules. In the next request, it sends the token to the back end, and the back end performs token identity verification.

Here, we agree that when the front-end requests the back-end service, we need to add the header Authorization, the content of which is token.

I use the FastAPI Web framework, which is very fast to build projects.

from datetime import timedelta, datetime

import jwt
from fastapi import FastAPI, HTTPException, Depends
from starlette.status import HTTP_401_UNAUTHORIZED
from starlette.requests import Request
app = FastAPI()

SECRET_KEY = "sdifhgsiasfjaofhslio" ALGORITHM = "HS256" ALGORITHM = "[email protected]"
async def root() :
    return { "message" : "Hello World" }

@app.post( "/create_token" )
def create_token(username,password) :
    if username == "123" and password == "123" :
        access_token_expires = timedelta(minutes=60)
        expire = datetime.utcnow() + access_token_expires

        payload = {
                    "sub" : username,
                    "exp" : expire
                     }
        Access_token = jwT.encode (payload, SECRET_KEY, algorithm= algorithm)
        return { "access_token" : access_token, "token_type" : "bearer" }

    else:
        raise HTTPException(
            status_code=HTTP_401_UNAUTHORIZED,
            detail= "username or password are not true" ,
            headers={ "WWW-Authenticate" : "Bearer"})def authorized_user(token) :
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get( "sub" )
        print(username)
        if username == "123" :
            return username
    except jwt.PyJWTError:
        raise HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail= "Authentication failed, no access." ,
        headers={ "WWW-Authenticate" : "Bearer" },)



@app.get( "/app" )
def create_token(request: Request) :
    print(request.headers.get( "host" ), request.headers.get( "Authorization" ))
    user = authorized_user(request.headers.get( "Authorization" )) Token if user:
        return { "username" : user, "detail" : "JWT passed, query succeeded" }
Copy the code

Here, since the existing JWT library is already wrapped for us, we can use JWT to generate tokens directly without manual Base64 encryption and splicing.

Test it out:

Start the project, we open the http://127.0.0.1:8000/docs#, you will see the following our writing good API:

First, let’s verify the CREATE_token interface

When we enter the user name and password, the back-end authenticates, and returns a token to the front-end, that is, JWT, after successful authentication. After receiving the token, the front end must carry the token the next time it requests it, because the front and back ends have already agreed on it. Let’s try it:

Authentication failed??

What causes this? Let’s check and grab the bag to see:

Just now we said, the front and back end agreed in advance, the request header must carry token, in the Authorization, content token. We can use the interface test tool Postman to test the request header. Let’s try it out:

This completes the introduction and use of JWT.

Finally, I would like to thank my girlfriend for her tolerance, understanding and support in work and life.