使用 Azure AD 的 NextAuth 刷新令牌

Wou*_*een 5 azure azure-active-directory next.js next-auth

由于访问令牌的默认有效时间为 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)
Run Code Online (Sandbox Code Playgroud)

我尝试在网上到处搜索,但根本找不到使用 Azure AD 和 NextAuth 的人(不是 B2C 版本,而是 B2B/组织版本)。

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

Wou*_*een 3

在提供的代码中,我犯了一个错误,将异步与 Promise 混合在一起(归功于 GitHub 上的 @balazsorban44)。这意味着return中的语句.then将值返回到发起获取请求的位置,而不是从refreshAccessToken()整个函数返回值。我放弃使用 Promise,只使用异步函数:

    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();
Run Code Online (Sandbox Code Playgroud)