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

Authentication With JWTs

Let's take a closer look at how JWTs work in the authentication flow.

Step 1: Login

It would be pretty annoying if you had to enter your username and password every time you wanted to make a request to an API. Instead, after a user enters a username and password, our server should respond with a token (JWT) that's saved in the client's device.

The token remains valid until it expires, at which point the user will need to log in again.

Step 2: Using the Token

When the user wants to make a request to the API, they send the token along with the request in the HTTP headers. The server can then verify that the token is valid, which means the user is who they say they are.

Assignment

function getBearerToken(req: Request): string;

Auth information will come into our server in the Authorization header. Its value will look like this:

Bearer TOKEN_STRING

This function should look for the Authorization header in the request and return the TOKEN_STRING if it exists (stripping off the Bearer prefix and whitespace). You can use the request's .get method. If the header doesn't exist, throw an error. This is an easy one to write a unit test for, and I'd recommend doing so.

Secrets should NOT be stored in Git, just in case anyone malicious gains access to your repository.

openssl rand -base64 64
{
  "password": "04234",
  "email": "[email protected]",
  "expiresInSeconds": 2
}

If it's specified by the client, use it as the expiration time. If it's not specified, use a default expiration time of 1 hour. If the client specified a number over 1 hour, use 1 hour as the expiration time.

Once you have the token, respond to the request with a 200 code and this body shape:

{
  "id": "5a47789c-a617-444a-8a80-b50359247804",
  "createdAt": "2021-07-01T00:00:00Z",
  "updatedAt": "2021-07-01T00:00:00Z",
  "email": "[email protected]",
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
}

Run and submit the CLI tests.