有人可以帮助我使用SSO AZURE登录吗?

kmpatx3s  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(114)

我在使用Azure的SSO时遇到问题。我使用Azure获取他们的令牌,然后将其发送到我们自己的后端,以便获得登录的授权。为此,我使用useMsal,并遵循弹出策略“const response = await instance.loginPopup(loginRequestPopup)"。当用户想要使用Azure登录时,会出现一个弹出窗口,用户选择帐户,我收到令牌,这将发送到我的后端,它是。这个问题,有时当用户选择帐户在这个新的azure标签,这个标签而不是关闭它自己,这重定向到登录屏幕,并不生成de令牌.之后,一切都失败了。有人能帮我吗我将向你展示我的代码。
功能:

export const handleAzureLogin = async ({ instance, loginRequestPopup, inProgress }: IAzureLogIn) => {
  try {
    const response = await instance.loginPopup(loginRequestPopup)
    const jwtToken = response.idToken
    console.log('JWT Token:', jwtToken)
    const bodyRequest = {
      type: 2,
      ssoToken: jwtToken,
    }
    const res = await sendTokenToBackend(bodyRequest)
    if (res.status === StatusCodes.OK) {
      return res
    } else {
      // Manejar el error del backend
      console.log('Backend error:', res)
      return res
    }
  } catch (error: any) {
    // Manejar errores en el proceso de inicio de sesión de Azure
    console.error('Azure login error:', error)

    return {
      status: StatusCodes.INTERNAL_SERVER_ERROR, // Ajusta el código de estado según sea necesario
      body: error.message,
    }
  }
}

export const sendTokenToBackend = async (bodyRequest: IBodyRequest) => {
  try {
    const response = await fetch('/api/login', {
      method: 'POST',
      body: JSON.stringify(bodyRequest),
    })

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`)
    }

    return {
      status: 200,
      body: response,
    }
  } catch (err: any) {
    console.log('Error sending token to backend:', err)
    return {
      status: 400,
      body: err.message,
    }
  }
}
export const msalConfig = {
  auth: {
    clientId: `${process.env.NEXT_PUBLIC_AZURE_CLIENT_ID}`,
    authority: `https://login.microsoftonline.com/${process.env.NEXT_PUBLIC_AZURE_KEY}`,
    redirectUri: `${process.env.NEXT_PUBLIC_AZURE_URL_REDIRECT}`,
  },
  cache: {
    cacheLocation: 'sessionStorage', // This configures where your cache will be stored
    storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
  },
  system: {
    loggerOptions: {
      loggerCallback: (level, message, containsPii) => {
        if (containsPii) {
          return
        }
        switch (level) {
          case LogLevel.Error:
            console.error(message)
            return
          case LogLevel.Info:
            console.info(message)
            return
          case LogLevel.Verbose:
            console.debug(message)
            return
          case LogLevel.Warning:
            console.warn(message)
            return
          default:
            return
        }
      },
    },
  },
}

export const loginRequest = {
  scopes: ['api://f50ace46-b2a0-4394-8d3d-8d72116f743c/Public.Read'],
}

export const graphConfig = {
  graphMeEndpoint: 'https://graph.microsoft.com/Public.Read',
}

export const loginRequestPopup = {
  ...loginRequest,
  prompt: 'select_account',
}

提前感谢!
我想避免这种奇怪的行为,并获得用户的登录。
重定向不起作用,所有登录失败。我想弥补这一切。

yacmzcpb

yacmzcpb1#

Nest try catch从缓存中获取静默令牌,如果过期,请使用Interactive/Popup:

var accounts = await app.GetAccountsAsync();

AuthenticationResult result = null;
try
{
     result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                       .ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
    // A MsalUiRequiredException happened on AcquireTokenSilent.
    // This indicates you need to call AcquireTokenInteractive to acquire a token
    Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

    try
    {
        result = await app.AcquireTokenInteractive(scopes)
                          .ExecuteAsync();
    }
    catch (MsalException msalex)
    {
        ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
    }
}
catch (Exception ex)
{
    ResultText.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
    return;
}

if (result != null)
{
    string accessToken = result.AccessToken;
    // Use the token
}

我知道你正在使用Angular,试试这样的东西:

MsalModule.forRoot(
        new PublicClientApplication({
            auth: {
                clientId: environment.azure.clientId,
                authority: environment.azure.cloudInstance + environment.azure.tenantId,
                redirectUri: environment.azure.redirectUri,
            },
            cache: {
                cacheLocation: "localStorage",
                storeAuthStateInCookie: isIE,
            },
        }),
        {
            interactionType: InteractionType.Popup,
            authRequest: {
                scopes: ["user.read"],
            },
        },
        {
            interactionType: InteractionType.Redirect,
            protectedResourceMap: new Map([
                ['/', [`${environment.azure.clientId}/openid`]],
            ]),
        }
    ),

相关问题