使用nextauth的Azure广告B2c自定义策略

bybem2ql  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(195)

我已经在我的应用程序中集成了Azure广告B2C用户流,它工作正常,但我需要在用户流中进行一些定制。因此,我做了一些自定义策略和验证策略部署的指导下,在azure广告b2c教程和一切都工作正常,如果尝试运行这些政策通过azure门户。我正在使用NextJs和NextAuth进行身份验证服务。NextAuth提供了Azure广告B2c提供程序,只要我用自定义策略名称更改用户流名称,它就可以很好地为用户流工作,我在注册和登录时出错。NextAuth AzureAdB2CProvider是否与Azure广告B2C自定义策略兼容?如何将其集成到我的应用程序中?

import axios from 'axios'
import config from 'config/config'
import jwtDecode from 'jwt-decode'
import { NextApiRequest, NextApiResponse } from 'next'
import NextAuth from 'next-auth'
import AzureADB2CProvider from 'next-auth/providers/azure-ad-b2c'

const b2cProviderName = 'azure-ad-b2c'
const nextAuthUrl = process.env.NEXTAUTH_URL
const clientId = process.env.AZURE_AD_B2C_CLIENT_ID
const tenantName = process.env.AZURE_AD_B2C_TENANT_NAME
const tenantGuid = process.env.AZURE_AD_B2C_TENANT_GUID
const clientSecret = process.env.AZURE_AD_B2C_CLIENT_SECRET
const jwtSecret = process.env.JWT_SECRET
let userFlow = process.env.AZURE_AD_B2C_PRIMARY_USER_FLOW

async function refreshAccessToken(token: any) {
  try {
    const url = `https://login.microsoftonline.com/${tenantGuid}/oauth2/v2.0/token`
    const response = await axios.post(
      url,
      {
        client_id: clientId,
        client_secret: clientSecret,
        scope: 'offline_access openid',
        grant_type: 'refresh_token',
        refresh_token: token.refresh_token
      },
      {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      }
    )

    return {
      ...token
      // id_token: refreshedTokens.id_token,
      // id_token_expires_at: refreshedTokens.expires_at * 1000,
      // refreshToken: refreshedTokens.refresh_token ?? token.refresh_token // Fall back to old refresh token
    }
  } catch (error) {
    console.error(error)

    return {
      ...token,
      error: 'RefreshAccessTokenError'
    }
  }
}
export const authOptions: any = {
  pages: {
    signIn: '/',
    signOut: '/auth/signout'
  },
  session: {
    maxAge: 24 * 60 * 60 * 60
  },
  secret: jwtSecret,
  callbacks: {
    async redirect({ url, baseUrl }: any) {
      return baseUrl
    },
    async session({ session, user, token }: any) {
      try {
        const response = await axios.post(
          `${config.SERVER}/api/user/createUser`,
          {},
          {
            headers: {
              Authorization: `Bearer ${token.id_token}`
            }
          }
        )
        if (token && response?.data?.payload) {
          session.id_token = token.id_token
          session.refresh_token = token.refresh_token
          session.id_token_expires_in = token.id_token_expires_in
          session.refresh_token_expires_in = token.refresh_token_expires_in
          session.firstName = response?.data?.payload?.firstname || ''
          session.roles = response?.data?.payload?.roles || []
          session.user.id = response?.data?.payload?.azure_id || ''
        }
        return session
      } catch (err) {
        console.error(err)

        return undefined
      }
    },
    async jwt({ token, user, account, profile, isNewUser }: any) {
      if (account) {
        token.id_token = account.id_token
        token.refresh_token = account.refresh_token
        token.id_token_expires_in = account.id_token_expires_in
        token.id_token_expires_at = account.expires_at * 1000
        token.refresh_token_expires_in = account.refresh_token_expires_in
        token.firstName = profile.name
      }
      // if (Date.now() < token.id_token_expires_at) {
      //   return token
      // }
      // return refreshAccessToken(token)
      return token
    }
  },
  providers: [
    AzureADB2CProvider({
      tenantId: tenantName,
      clientId: clientId || '',
      clientSecret: clientSecret || '',
      primaryUserFlow: userFlow,
      authorization: {
        params: {
          scope: `https://${tenantName}.onmicrosoft.com/api/demo.read https://${tenantName}.onmicrosoft.com/api/demo.write offline_access openid`,
          p: `${userFlow}`
        }
      },
      checks: ['pkce'],
      client: {
        token_endpoint_auth_method: 'none'
      }
    })
  ]
}

export default (req: NextApiRequest, res: NextApiResponse) => {
  return NextAuth(req, res, authOptions)
}

这是我[nextauth].tsx文件供参考

ncgqoxb0

ncgqoxb01#

自定义策略会出现什么错误?
您可能需要使用AppInsights来查看日志。
如果使用门户上的“立即运行”按钮,自定义策略是否有效?
理论上,您需要做的就是更改策略名称,这应该可以工作。

相关问题