WaspW
Wasp17mo ago
96 replies
sion0921

How to generate Authorization header JWT token for custom API endpoint?

I've created operation which generates JWT token which is sent to my chrome extension.

action generateExtensionToken {
  fn: import { generateExtensionToken } from "@src/auth/extensionAuth",
  entities: [User]
}
...
api improve {
  fn: import { improve } from "@src/api/improve",
  httpRoute: (POST, "/spellxy/improve"),
  auth: true
}

The main goal is to access context.user for my custom API endpoint to verify if the user has a paid plan.
I've tried many combinations, using userId, username, and even config.auth.jwtSecret instead of my JWT_SECRET_KEY in env.server, but none of these work with auth:true for api endpoint in a Postman request that includes a generated bearer token.

import jwt from 'jsonwebtoken';
import { HttpError } from 'wasp/server';
import { config } from 'wasp/server';

export const generateExtensionToken = async (args, context) => {
  if (!context.user) {
    throw new HttpError(401, 'Not authorized');
  }

  const token = jwt.sign({ userId: context.user.id }, config.auth.jwtSecret, { expiresIn: '1y' });

  return { token };
};


What's the right format to sign a JWT token for it to work with a custom API endpoint to access context.user?

EDIT: I used the client-side sessionId for a custom API endpoint; however, some questions still remain
Was this page helpful?