gpt4 book ai didi

azure - 使用 MSAL 保护 Azure Function API

转载 作者:行者123 更新时间:2023-12-05 01:30:02 25 4
gpt4 key购买 nike

我有 Azure Functions,我想使用访问 token 进行身份验证。

我设置了以下内容

  1. Angular SPA 使用 Azure 应用程序对用户进行身份验证
  2. 用于调用图形 API 的访问 token ,权限在 Azure 应用程序中设置(第 1 点)
  3. Azure Function 具有 SPA 使用的 http 触发器 (API)

目前,API 是匿名的,可以从任何地方调用。我想使用图形 api 使用的访问 token 来保护这些 api(第 2 点)

我认为对我来说最好的方法是 AAD Multi-Tenancy 身份验证。但是,当我单击“身份验证(经典)”时,它会给我此应用程序是使用新的身份验证体验进行配置的。单击此处访问身份验证(预览)。

Currently, I have kept the authentication as "allow unauthenticated requests"

此外,如果我继续使用以下选项进行身份验证,我会收到“您无权查看此目录或页面。”错误

enter image description here

我在网上找到的大多数文章都在谈论 AAD。对我来说,该选项未启用。

我尝试了以下文章来使其发挥作用,但不知何故它没有发生。谁能建议一下。我怎样才能做到这一点。

https://medium.com/medialesson/protecting-azure-function-apps-with-azure-ad-authentication-authorization-fd167ce4fe33

https://medium.com/geekculture/easyauth-in-functions-app-with-azure-active-directory-29c01cad8477

我需要在现有的 Azure 应用程序中执行某些操作才能使其正常工作吗?

最佳答案

据我了解,您的 Azure 函数受 AAD 使用身份验证(轻松身份验证)的保护。现在,您的 Angular SPA 想要访问此功能。请按照以下步骤操作:

  1. 转到 Azure AD => 应用注册 => 您为保护 Azure 功能而创建的应用 => 公开 API 以添加范围,例如 access_as_user这样您的 SPA 可能需要此范围的访问 token :

enter image description here

  • 前往 Azure AD => 应用注册 => 您为 SPA 应用创建的应用 => API 权限 => 添加权限 => 我的 API 以授予我们刚刚创建的范围:
  • enter image description here enter image description here

    单击授予管理员同意按钮以完成该过程。

  • 在您的 SPA 应用中,使用 MsalService获取范围为 api://<your azure function app id>/access_as_user 的访问 token ,通过此 token ,您可以访问您的 Azure 函数。为了快速测试,我只是在 post man 中测试它,它工作得很好:
  • 不使用此访问 token

    enter image description here

    携带此访问 token enter image description here

    更新

    基本上,您的应用程序请求图如下:

    SPA(带有访问 token 的请求)==> Azure函数的轻松身份验证(验证 token ,如果通过,则进入Azure函数代码逻辑,如果没有,返回401)==> Azure函数的代码逻辑(obo流到获取 Graph API 的访问 token )==> 调用 Microsoft Graph API

    到目前为止,我们已经完成了步骤 1 和 2:获取用于轻松身份验证的访问 token ,并将简单例份验证传递到 Azure 函数代码逻辑。

    因此在Azure函数代码逻辑中,我们需要做两件事:

    1. 获取请求 header 中的访问 token
    2. 使用访问 token 和 OBO 流为 Microsoft Graph API 交换新的访问 token 。只需引用下面的请求即可使用OBO flow交换 Microsoft Graph API 的访问 token : enter image description here

    顺便说一句,请确保您的Azure函数应用程序已被授予权限user.readCalendars.Read :

    enter image description here

    这样您就可以获得新的访问 token 来调用 Microsoft Graph API: enter image description here

    关于azure - 使用 MSAL 保护 Azure Function API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67421341/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com