We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

JWTs

There are several different ways to handle authentication. We'll use JWTs in this course. They're a popular choice for APIs that are consumed by web applications and mobile apps.

What Is a JWT?

A JWT is a JSON Web Token. It's a cryptographically signed JSON object that contains information about the user. You'll learn about how the cryptography of JWTs work in our Learn Cryptography course, for now, it's just important to know that once the token is created by the server, the data in the token can't be changed without the server knowing.

When your server issues a JWT to Bob, Bob can use that token to make requests as Bob to your API. Bob won't be able to change the token to make requests as Alice.

Assignment

The first building blocks you'll write are the functions for creating and validating JWTs, which will be used in the next lesson to authenticate users.

  1. func MakeJWT(userID uuid.UUID, tokenSecret string, expiresIn time.Duration) (string, error)
    

    Create and return a JWT using this JWT library, which you can import into your code by running:

    go get -u github.com/golang-jwt/jwt/v5
    
  2. func ValidateJWT(tokenString, tokenSecret string) (uuid.UUID, error)
    
  3. If all is well with the token, use the token.Claims interface to get access to the user's id from the claims (which should be stored in the Subject field). Return the id as a uuid.UUID.

Run and submit the CLI tests.