带有Azure AD的NextAuth刷新令牌

rjee0c15  于 2023-01-30  发布在  其他
关注(0)|答案(1)|浏览(168)

由于访问令牌的默认有效时间是1小时,我尝试让刷新令牌在我的应用程序中工作。我已经被这个问题困扰了几个星期,似乎无法修复它。我已经验证了我的refreshAccessToken(accessToken)函数是否工作(其中accessToken是一个带有过期令牌、刷新令牌和其他一些东西的对象)。
我将问题定位到async session()函数。虽然在async jwt()函数中调用了refreshAccessToken,但async session()函数仍会导致错误,因为参数**token未定义**。这会导致错误cannot read property accessToken from undefined(因为token.accessToken在第一行)我怎样才能解决这个问题,并且在将访问令牌和所有其他信息一起发送到客户端之前,使函数async session()等待访问令牌刷新呢(组、用户名等)?

/**
 * All requests to /api/auth/* (signIn, callback, signOut, etc.) will automatically be handled by NextAuth.js.
 */

import NextAuth from "next-auth"
import AzureAD from "next-auth/providers/azure-ad";

async function refreshAccessToken(accessToken) {
  try {
    const url = "https://login.microsoftonline.com/02cd5db4-6c31-4cb1-881d-2c79631437e8/oauth2/v2.0/token"
    await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: `grant_type=refresh_token`
      + `&client_secret=${process.env.AZURE_AD_CLIENT_SECRET}`
      + `&refresh_token=${accessToken.refreshToken}`
      + `&client_id=${process.env.AZURE_AD_CLIENT_ID}`
    }).then(res => res.json())
      .then(res => {
        return {
          ...accessToken,
          accessToken: res.access_token,
          accessTokenExpires: Date.now() + res.expires_in * 1000,
          refreshToken: res.refresh_token ?? accessToken.refreshToken, // Fall backto old refresh token
        }
      })
  } catch (error) {
    console.log(error)

    return {
      ...accessToken,
      error: "RefreshAccessTokenError",
    }
  }
}

export const authOptions = {
  providers: [
    AzureAD({
      clientId: process.env.AZURE_AD_CLIENT_ID,
      clientSecret: process.env.AZURE_AD_CLIENT_SECRET,
      tenantId: process.env.AZURE_AD_TENANT_ID,
      authorization: {
        params: {
          scope: "offline_access openid profile email Application.ReadWrite.All Directory.ReadWrite.All " +
            "Group.ReadWrite.All GroupMember.ReadWrite.All User.Read User.ReadWrite.All"
        }
      }
    }),
  ],
  callbacks: {
    async jwt({token, account, profile}) {
      // Persist the OAuth access_token and or the user id to the token right after signin
      if (account && profile) {
        token.accessToken = account.access_token;
        token.accessTokenExpires = account.expires_at * 1000;
        token.refreshToken = account.refresh_token;

        token.id = profile.oid; // For convenience, the user's OID is called ID.
        token.groups = profile.groups;
        token.username = profile.preferred_username;
      }

      if (Date.now() < token.accessTokenExpires) {
        return token;
      }

      return refreshAccessToken(token);
    },
    async session({session, token}) {
      // Send properties to the client, like an access_token and user id from a provider.
      session.accessToken = token.accessToken;
      session.user.id = token.id;
      session.user.groups = token.groups;
      session.user.username = token.username;

      const splittedName = session.user.name.split(" ");
      session.user.firstName = splittedName.length > 0 ? splittedName[0] : null;
      session.user.lastName = splittedName.length > 1 ? splittedName[1] : null;

      return session;
    },
  },
  pages: {
    signIn: '/login',
  }
}

export default NextAuth(authOptions)

我试着在网上到处搜索,但甚至很难找到使用带有NextAuth的Azure AD的人(不是B2C版本,而是B2B/组织版本)。

TLDR:使用refreshToken获取新的accessToken有效,但NextAuth不会将此令牌传递到前端,而是抛出错误,因为在async session()中,令牌未定义。

f5emj3cl

f5emj3cl1#

在提供的代码中,我犯了一个错误,把async和promise混在了一起(归功于GitHub上的@balazsorban44)。这意味着.then中的return语句返回的是初始化获取请求的值,而不是从函数refreshAccessToken()中返回一个完整的值。我不再使用promise,只使用了一个async函数:

const req = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: `grant_type=refresh_token`
      + `&client_secret=${process.env.AZURE_AD_CLIENT_SECRET}`
      + `&refresh_token=${accessToken.refreshToken}`
      + `&client_id=${process.env.AZURE_AD_CLIENT_ID}`
    })

    const res = await req.json();

相关问题