Skip to content

getToken returns next-auth issued JWT? - can I get my provider issued JWT insteadΒ #3719

@colin-riddell

Description

@colin-riddell

Question πŸ’¬

Hello people of NextAuth.

Loving the library so far, though I've been quite confused with the api side getToken() call. My understanding after doing some digging is that it's getting a JWT that next-auth has issued? I actually don't want that..

I want the JWT access token that my auth provider (in my case cognito) has issued, so that I can use it in a back-end API call, to my other non-next API which is acting as my oauth resource server I want to do that in next api back-end. So something along the lines of:

// /api/someroute.ts

import { getToken } from "next-auth/jwt";

const getJwt = async (req: NextApiRequest) => {
  return await getToken({ req, secret, raw: true });  // doesn't work without raw: true for some reason?
};

export default async function handler(req: NextApiRequest, res: NextApiResponse) {

  const accessToken = await getJwt(req);

  if (req.method === "POST") {
    fetch("http://non-next-service", headers: { "Authorization": `Bearer ${accessToken}`})
     //etc
  }
}

Upon logging in next-auth spits out some profile and account details to the terminal including id_token, access_token and refresh_token. Using the access_token in POSTman to call my resource server works perfectly! But it's clearly not the same token that's coming from getToken().

I've read about the callback options in the next-auth config and see there's a callback for jwt and session. It's not that clear to me what they're useful for, or how it's connected to what happens with getToken.

Looking through other issues and the example project I can't honestly see what I'm doing wrong.

Any help or pointers greatly appreciated.

How to reproduce β˜•οΈ

// /api/someroute.ts

import { getToken } from "next-auth/jwt";

const getJwt = async (req: NextApiRequest) => {
  return await getToken({ req, secret, raw: true });  // doesn't work without raw: true for some reason?
};

export default async function handler(req: NextApiRequest, res: NextApiResponse) {

  const accessToken = await getJwt(req);

  if (req.method === "POST") {
    fetch("http://non-next-service", headers: { "Authorization": `Bearer ${accessToken}`})
     //etc
  }
}

Contributing πŸ™ŒπŸ½

Yes, I am willing to help answer this question in a PR

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionAsk how to do something or how something works

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions