Access Tokens

When a user completes their authentication on the hosted auth page, they will be redirected back to your application. With this redirect, an access token is included that you can use to authenticate the user in your application.

The access token is a JWT which expires after seven days and is signed with the access token secret, that can be viewed in the User Management settings in the dashboard.

Validating the Token

To validate the token, you can use the JWT library for your language of choice.

const jwt = require('jsonwebtoken');
const secret = process.env.ANZU_ACCESS_TOKEN_SECRET;

function validateToken(token) {
  return new Promise((resolve, reject) => {
    jwt.verify(
      token,
      secret,
      { algorithms: ["HS256"] },
      (err, decoded) => {
        if (err) {
          reject(err);
        } else {
          resolve(decoded);
        }
      }
    );
  });
}
js

With some helper functions, you can read the Authorization header, validate the token, and return the user ID.

const app = require('express')();

async function getPostsByUser(userId) {
    // ...
    return [];
}

function authMiddleware() {
  return async (req, res, next) => {
    const authHeader = req.headers['authorization'];
    if (!authHeader) {
      return res.status(401).send('No token provided.');
    }
    
    const token = authHeader.replace('Bearer ', '');

    try {
      const decoded = await validateToken(token);
      req.userId = decoded.sub;
      next();
    } catch (err) {
      return next(err);
    }
  };
}

function currentUserId(req) {
    return req.userId;
}

app.use(authMiddleware());

app.get("/posts", async (req, res) => {
    const userId = currentUserId(req);
    const posts = await getPostsByUser(userId);
    res.send(posts);
});

app.listen(3000);
js

Token Payload

The token encodes the following information:

{
  "alg": "HS256",
  "typ": "JWT",
  "kid": "<environmentId>"
}
json

The payload looks like the following:

{
  "iat": 1662209363,
  "exp": 1662814163,
  "iss": "api.anzuhq.com",
  "sub": "<userIdentityId>",
  "jti": "<accessTokenId>"
}
json

Related