通过 Azure AD 使用客户端凭据保护 API

Securing API with client credentials via Azure AD

我有一个 ASP.NET Core API 托管在 Azure 中,可供多个受信任的客户端访问。我希望提供一个接受 client_id 和 client_secret 的 /auth 端点。响应将是一个过期的 OAuth 访问令牌。

我发现的许多 examples/tutorials 主要与 username/password 登录和完整的 OAuth 流程 (B2C) 有关,这不是我要找的,因为受信任的客户有秘密。

我一直在关注 Azure API Management,它链接到用于 OAuth 的 Azure AD,但我认为这只是让事情现在变得复杂。

过去我使用 ASP.NET 中间件生成并验证了 JWT 不记名令牌,但我确定我应该通过 Azure AD 生成和验证令牌 - 或者我在这里错了吗?

[期望因为没有明确的代码相关而得到一些反对票,但真的需要一些建议才能让我通过这个]

I wish to offer an /auth endpoint which accepts a client_id and client_secret. Response will be an OAuth access token with expiry.

您可以使用 client credential flow。然后您可以使用此端点获取访问令牌。

POST /{tenant}/oauth2/v2.0/token HTTP/1.1           //Line breaks for clarity
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

client_id=535fb089-9ff3-47b6-9bfb-4f1264799865
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&client_secret=qWgdYAmab0YSkuL1qKv5bPX
&grant_type=client_credentials

在执行此操作之前,您需要 expose application permissions 您的应用程序 api。 appRoles内容如下

"appRoles": [
    {
    "allowedMemberTypes": [ "Application" ],
    "description": "Accesses the TodoListService-Cert as an application.",
    "displayName": "access_as_application",
    "id": "ccf784a6-fd0c-45f2-9c08-2f9d162a0628",
    "isEnabled": true,
    "lang": null,
    "origin": "Application",
    "value": "access_as_application"
    }
],