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

How to update the session after refresh JWT token? #1357

Closed
Feradik opened this issue Feb 22, 2021 · 4 comments
Closed

How to update the session after refresh JWT token? #1357

Feradik opened this issue Feb 22, 2021 · 4 comments
Labels
question Ask how to do something or how something works stale Did not receive any activity for 60 days

Comments

@Feradik
Copy link

Feradik commented Feb 22, 2021

Hi there!

Your question

How to update next-auth.session-token cookie from server side?

What are you trying to do

I'm implementing the refresh token for custom provider.
So, I have next-auth options as below:

export default (req: NextApiRequest, res: NextApiResponse) =>
    NextAuth(req, res, {
        providers: [
   {
    id: "id",
    name: "name",
    type: "oauth",
    version: "2.0",
    scope: "",
    params: { grant_type: "authorization_code" },
    accessTokenUrl: <url>,
    authorizationUrl: <url>,
    profileUrl: <url>,
    clientId: <client>,
    clientSecret: <secret>,
    profile: (profile: GenericObject) => ({
        id: profile.id,
        email: profile.email,
        image: profile.image,
    }),
}
  ],
        callbacks: {
            async session(session, token: GenericObject) {
                return {
                    ...session,
                    user: token.user,
                    accessToken: token.accessToken,
                    refreshToken: token.refreshToken,
                };
            },
            async jwt(token, user, account) {
                // Initial sign in
                if (account && user) {
                    return {
                        accessToken: account.access_token,
                        accessTokenExpires: Date.now() + account.expires_in * 1000,
                        refreshToken: account.refresh_token,
                        user,
                    };
                }

                // Return previous token if the access token has not expired yet
                if (Date.now() < token.accessTokenExpires) {
                    return token;
                }

                // Access token has expired, try to update it
                return refreshAccessToken(token);
            },
        },
        secret: "MY_SECRET",
    });

Also I have an API endpoint where I try to get the session via helper getSession({req}).

// api endpoint - /api/send-form.ts
async function handler(req: NextApiRequest, res: NextApiResponse) {
    const session = await getSession({ req });

     // need to do api call from another service
    const response = await axios.post(
        '<url>',
       formData,
        {
            headers: {
                Accept: "application/json",
                Authorization: `Bearer ${session.accessToken}`,
            },
        },
    );

    res.status(200).json({data: []});
}

So, it works fine until need to refresh token.
My example:

  • the user logs in an gets the access token with expiration time - 1 hour
  • fill out the form and not submit it - leaves the open tab with form
  • the user returns to the page in 1.5 hours and press a submit button - the access token is already not valid - need to refresh it
  • the form data sends to /api/send-from - there I can get the refreshed token from the session
  • but next run of the jwt callback - the token will old one (not refreshed previous) from cookie
  • next the session from getSession() will be with old access token (refreshed token is lost)

If user switches between any tabs and returns to the form page it runs the /api/auth/session and updates the cookies.

Does anybody know how to update the cookie correctly?

@Feradik Feradik added the question Ask how to do something or how something works label Feb 22, 2021
@unsphere
Copy link

unsphere commented Mar 11, 2021

What about using getToken() instead of getSession()?

import { getToken } from 'next-auth/jwt';
import axios from 'axios';

export default async (req, res) => {
  const token = await getToken({ req, secret: process.env.JWT_SECRET });
  
  if (!token) {
    return res.status(401).json({ status: 401, message: 'Unauthorized' });
  }
  
  let accessToken = token.accessToken;
  if (Date.now() >= token.accessTokenExpires) {
    const refreshToken = await refreshAccessToken(token);
    accessToken = refreshToken.accessToken;
  }
  
  const response = await axios.post(
      '<url>',
     formData,
      {
          headers: {
              Accept: "application/json",
              Authorization: `Bearer ${accessToken}`,
          },
      },
  );
  
  res.status(200).json({data: response.data});
};

@avisra
Copy link

avisra commented Mar 29, 2021

@ramiel Did you eventually get past this issue? I was running into the same thing

@stale
Copy link

stale bot commented May 28, 2021

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 it open. (Read more at #912) Thanks!

@stale stale bot added the stale Did not receive any activity for 60 days label May 28, 2021
@stale
Copy link

stale bot commented Jun 4, 2021

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
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

3 participants