Giter Site home page Giter Site logo

Comments (7)

Thanaen avatar Thanaen commented on May 31, 2024 1

@viachaslau-latushkin ➡️ vercel/next.js#49442 (comment)

from iron-session.

arthurjdam avatar arthurjdam commented on May 31, 2024 1

You can use sealData() and unsealData() to encrypt/decrypt the cookie values.

Assuming you're doing an oauth/refresh token kind of thing, here's something I used recently:

import {
  IRON_COOKIE_NAME,
  SessionData,
  ironOptions,
} from './auth';

export async function middleware() {
  const session = await getIronSession<SessionData>(cookies(), ironOptions);
  const next = NextResponse.next();

  if (!session.token?.expires_at) {
    // no/invalid token, send user to auth
    return NextResponse.redirect(getGoogleAuthURL());
  }
  if (session.token.expires_at < Date.now()) {
    // refresh token
    try {
      const token = await refreshToken(session.token);

      const sealed = await sealData(
        {
          ...session,
          token: { ...token, expires_at: Date.now() + token.expires_in * 1000 },
        },
        ironOptions,
      );
      next.cookies.set(IRON_COOKIE_NAME, sealed);
      // await session.save(); // won't work
    } catch (e) {
      // some error while refreshing token, send user to auth
      console.error(e);
      return NextResponse.redirect(getGoogleAuthURL());
    }
  }

  return next;
}

from iron-session.

viachaslau-latushkin avatar viachaslau-latushkin commented on May 31, 2024

@viachaslau-latushkin ➡️ vercel/next.js#49442 (comment)

Thank you!
But in this case cookie from middleware is not encrypted.

from iron-session.

Thanaen avatar Thanaen commented on May 31, 2024

Hello @viachaslau-latushkin ,
iron-session adds the encrypted cookie via the "set-cookie" header, so the applySetCookie method applies the correctly encrypted cookie!

What makes you think otherwise?

from iron-session.

viachaslau-latushkin avatar viachaslau-latushkin commented on May 31, 2024

@Thanaen in middleware I am trying to apply refresh token logic.
I get a new token and try to rewrite cookie with new encrypted (encrypted token) value.
Yes, applySetCookie really add new cookie from middleware and it exists in next steps.
But how get new encrypted value with help of iron-session which will be encrypted in middleware with help of sessionOptions.password and after successfully decrypt this value (again with help of sessionOptions.password) in time of SSR or in Api Router handler?

from iron-session.

viachaslau-latushkin avatar viachaslau-latushkin commented on May 31, 2024

@arthurjdam
Thank you.
Nice solution.
And good point to read documentation from start to end.

from iron-session.

MalakJoseph avatar MalakJoseph commented on May 31, 2024

As @arthurjdam solution, here's the updated version that worked for me. Hope it may save time for others.

This solution fixes the error Cookies can only be modified in a Server Action or Route Handler after calling the await session.save().

middleware.ts

export default async function middleware(req: NextRequest) {
  const { isLoggedIn, exp } = await getSession();

  // Refresh Token Rotation
  if (isLoggedIn && exp && exp < Date.now() / 1000) {
    try {
      const newSession = await refreshToken();
      const sealed = await sealData(newSession, sessionOptions);
      const res = NextResponse.redirect(req.url);

      res.cookies.set({
        name: '[your-cookie-name]',
        value: sealed,
      });
      return res;
    } catch (e) {
      await logout();
    }
  }
  
  return NextResponse.next();
}

authActions.ts

export async function getSession() {
  return await getIronSession<User>(cookies(), sessionOptions);
}

export async function refreshToken() {
  const session = await getSession();
  const res = await fetch(
    `${process.env.NEXT_PUBLIC_BACKEND_BASE_URL}/user/refresh`,
    {
      method: 'POST',
      headers: { Authorization: 'Bearer ' + session.refreshToken },
    }
  );
  const { accessToken, refreshToken } = await res.json();
  const newUser = jwt.decode(accessToken) as JwtPayload;

  session.userToken = accessToken;
  session.refreshToken = refreshToken;
  session.exp = newUser.exp;

  return session;
}

P.S. I'm assuming the interface of my User object is:

export interface User {
  id: string;
  isLoggedIn: boolean;
  name: string;
  userToken: string;
  refreshToken: string;
  exp: number | undefined;
}

I'm available for any further clarifications or inquiries...

from iron-session.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.