Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unsure how to get my JWT session token #608

Closed
2 of 5 tasks
JaredCE opened this issue Aug 26, 2020 · 7 comments
Closed
2 of 5 tasks

Unsure how to get my JWT session token #608

JaredCE opened this issue Aug 26, 2020 · 7 comments
Labels
docs Relates to documentation question Ask how to do something or how something works stale Did not receive any activity for 60 days

Comments

@JaredCE
Copy link

JaredCE commented Aug 26, 2020

Your question
I have a Server side rendered page where I need to grab the JWT session token from my user, but i'm a little unsure how to go about getting it.

What are you trying to do
I want to get the JWT session token from my user on a server side rendered page... my code looks like this on the page:

import { signIn, signOut, useSession, getSession } from 'next-auth/client';

const Generate = () => {
  const [ session, loading ] = useSession();

  return (...)
}

export async function getServerSideProps(context) {
    const session = await getSession(context);
    console.log(session)
    return {
      props: {

      }
    }
}

However, this outputs:

{
  user: { name: 'Jared Evans', email: 'jared@example.com', image: null },
  expires: '2020-09-25T17:02:27.420Z'
}

I'm using a custom oAuth provider so my [...nextauth].js looks like this:

{
      id: 'blah',
      name: 'blah',
      type: 'oauth',
      version: '2.0',
      accessTokenUrl: 'https://auth.example.com/oauth/token',
      authorizationUrl: 'https://auth.example.com/dialog/authorise?response_type=code',
      profileUrl: 'https://auth.example.com/api/userinfo',
      scope: [],
      params: { grant_type: 'authorization_code' },
      profile: (profile) => {
        return {
          id: profile.identifier,
          name: profile.cn + ' ' + profile.sn,
          email: profile.email,
        };
      },
      clientId: 'blah',
      clientSecret: 'secretBlah',
      session: { jwt: true },
      callbacks: {
        jwt: async (token, user, account, profile, isNewUser) => {
          console.log('here');
          console.log(token);
          console.log(user);
          const isSignIn = (user) ? true : false
          // Add auth_time to token on signin in
          if (isSignIn) { token.auth_time = Math.floor(Date.now() / 1000) }
          return Promise.resolve(token)
        },
        session: async (session, token) => {
          console.log('here2');
          console.log(token);
          console.log(session);
          if (!session?.user || !token?.account) {
            return session
          }

          session.user.id = token.account.id
          session.accessToken = token.account.accessToken

          return session
        }
      }
    },

I suspect it's to do with my callbacks but none of my console.logs are triggering on the generate page.

Feedback
Documentation refers to searching through online documentation, code comments and issue history. The example project refers to next-auth-example.

  • Found the documentation helpful
  • Found documentation but was incomplete
  • Could not find relevant documentation
  • Found the example project helpful
  • Did not find the example project helpful
@JaredCE JaredCE added the question Ask how to do something or how something works label Aug 26, 2020
@iaincollins
Copy link
Member

Hi there,

Ah the session and callback options go further up, at the same level as the providers option (not inside the provider).

session: { jwt: true },
callbacks: {
  jwt: async (token, user, account, profile, isNewUser) => {
    console.log('here');
    console.log(token);
    console.log(user);
    const isSignIn = (user) ? true : false
    // Add auth_time to token on signin in
    if (isSignIn) { token.auth_time = Math.floor(Date.now() / 1000) }
    return Promise.resolve(token)
  },
  session: async (session, token) => {
    console.log('here2');
    console.log(token);
    console.log(session);
    if (!session?.user || !token?.account) {
      return session
    }

    session.user.id = token.account.id
    session.accessToken = token.account.accessToken

    return session
  }
}

If you move them, what you are doing should work. :-) The documentation isn't as clear on this as it could be.

You can also use the getToken method server side, but actually I'd do what you are already doing and only go down that route if you think you need to (it's really intended for API routes and probably best not to use it in a Next.js page).

@LoriKarikari LoriKarikari added the docs Relates to documentation label Aug 29, 2020
@stale
Copy link

stale bot commented Dec 5, 2020

Hi there! It looks like this issue hasn't had any activity for a while. It will be closed if no further activity occurs. If you think your issue is still relevant, feel free to comment on it to keep ot open. Thanks!

@stale stale bot added the wontfix This will not be worked on label Dec 5, 2020
@balazsorban44 balazsorban44 added stale Did not receive any activity for 60 days and removed wontfix This will not be worked on labels Dec 5, 2020
@stale
Copy link

stale bot commented Dec 12, 2020

Hi there! It looks like this issue hasn't had any activity for a while. To keep things tidy, I am going to close this issue for now. If you think your issue is still relevant, just leave a comment and I will reopen it. (Read more at #912) Thanks!

@stale stale bot closed this as completed Dec 12, 2020
@mcnaveen
Copy link

mcnaveen commented Aug 3, 2022

I'm kinda facing a similar issue. I have trouble getting accessToken from the session.

Using MongoDB and EmailProvider method for Sign In.

Since this issue is a bit old. I assume things are changed.

This is how my [...nextauth].js file looks like.

import NextAuth from "next-auth";
import { MongoDBAdapter } from "@next-auth/mongodb-adapter";
import EmailProvider from "next-auth/providers/email";
import MongoClientPromise from "../../../lib/mongodb";

const THIRTY_DAYS = 30 * 24 * 60 * 60;
const THIRTY_MINUTES = 30 * 60;

export default NextAuth({
  secret: process.env.SECRET,
  session: {
    strategy: "jwt",
    maxAge: THIRTY_DAYS,
    updateAge: THIRTY_MINUTES,
  },

  adapter: MongoDBAdapter(MongoClientPromise),
  providers: [
    EmailProvider({
      server: {
        host: process.env.EMAIL_SERVER_HOST,
        port: process.env.EMAIL_SERVER_PORT,
        auth: {
          user: process.env.EMAIL_SERVER_USER,
          pass: process.env.EMAIL_SERVER_PASSWORD,
        },
      },
      from: process.env.EMAIL_FROM,
    }),
  ],
});

When I tried to extract the accessToken from the session in the pages/index.js it's showing undefined.

@AmruthPillai
Copy link

Could someone help me understand how I can retrieve the jwt token on client side? (with and without hooks)

@SemajDraw
Copy link

SemajDraw commented Sep 5, 2022

next-auth-example

Why is this not documented? It's essential and basic functionality. JWT is not present in the session and the token property in the JWT call back is the decrypted token which contains a subset of the user object... why?

Do we nee to to manually read the cookies and handle token retrieval for api requests not performed by next auth?

@frouo
Copy link

frouo commented May 31, 2023

@SemajDraw I had the same question but I found this from @iaincollins:

The JWT for NextAuth.js isn't readable by the browser by design (following best practice, to prevent XSS and session hijacking by third party scripts)

cf. #643 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs Relates to documentation question Ask how to do something or how something works stale Did not receive any activity for 60 days
Projects
None yet
Development

No branches or pull requests

8 participants