JWT tokens & Go (Golang): Easy explanation

Wacław The Developer
2 min readDec 11, 2021
Photo by VIRUL on Unsplash

Hi everybody! Today I want to clarify such topic as JWT. Maybe you feel confused if you used “check the password & generate md5(random_string) to store user`s session” before because today JWT became the standard of the area. (Don't use md5 in 2021). So, let's go!

What problem we are trying to solve?

What we are doing after checking of username and password? Right. We need to generate credentials to avoid comparison of username and password every time when user performs API request. So, what we can do? Many people use the such aproach:

  1. Check username&password
  2. Save hash(random_string) in DB, associated with user_id
  3. Send hash(random_string) to user to use as credentials for API
  4. Get user_id accosiated with credentials from db every API request

So, what’s the problem with that approach?

The cons of this approach are:

  1. We need to store any additional information about credentials on server side. For example: expire time, access scopes, etc.
  2. In case of DB leakage — credentials details can be used to access some resources without our knowledge.

How JWT can handle this?

Avoiding some theory — JWT token is the JSON string, signed with cryptokey. That is easy. To explain how we can use it:

  1. Check username&password
  2. Create JSON with such data:
{
"user_id": 1111, // User ID in system
"expire": 1639211179, // Timestamp with expire time
"scope": "read, write" // Access levels for credentials
// Any other info related to credentials
}

3. Sign it by 256-length key

4. Send the result to client to use as token

5. Check the sign of token and parse token to use the trusted data from step 2 on every API call

So, after that, we don`t store any information related to credentials in DB.

Let's code!

To work with JWT we will use https://github.com/golang-jwt/jwt lib.

How to generate JWT token:

How to parse and verify the token:

Pros:

  • We don’t need to store any details in DB
  • It is a good way to avoid leakage of credentials details

Cons:

  • We can’t revoke the token before token expiration. Way to fix that: add meta info to JSON and store it in Redis or other storage. Check existence of that string on API call received

Instead of conclusion:

Thanks for your attention and don’t be confused to ask questions

--

--