API管理中的身份验证:Entra ID的实践与挑战

在API管理中,身份验证是保障系统安全性的关键环节。最近,我尝试在Azure API Management (APIM) 的Basic层级中集成Microsoft Entra ID (前Azure AD) 进行身份验证,并在过程中遇到了几个有趣的挑战和解决方案。本文将详细介绍这个过程,并提供一些实例来帮助大家更好地理解。

背景介绍

Azure API Management提供了一个名为Entra ID的身份验证解决方案,该解决方案在标准或更高层级中是默认支持的。然而,在Basic层级中,官方文档明确指出不支持Entra ID。但这并没有阻止我们尝试通过手动配置来实现这个功能。

手动配置Entra ID

根据微软文档《How to add AAD》,我们可以手动启用Entra ID并设置身份提供者。以下是具体步骤:

  1. 创建Azure AD应用

    • 在Azure AD中创建一个新的应用注册。
    • 配置重定向URI以便于API管理服务进行回调。
  2. 配置API Management

    • 在APIM实例中,导航到"Identities"选项卡,并添加Azure AD作为身份提供者。
    • 填写必要的信息,如客户端ID、客户端密钥、租户ID等。
  3. 发布开发者门户

<think> 我们被要求回答如何在ASP.NET 4.8项目中集成Microsoft Entra ID(原名Azure AD)。根据提供的引用,虽然引用主要针对ASP.NET Core,但我们可以结合引用中的概念和一般性知识来回答。注意:ASP.NET 4.8(即传统的ASP.NET,非Core)的集成方式ASP.NET Core有所不同。 在ASP.NET 4.8中,我们可以使用Owin中间件来集成Microsoft Entra ID。主要步骤包括: 1. 在Azure门户中注册应用程序。 2. 在项目中安装必要的NuGet包(如Microsoft.Owin.Security.OpenIdConnect, Microsoft.Owin.Security.Cookies等)。 3. 配置Owin启动类,设置OpenID Connect认证中间件。 具体步骤: ### 1. 在Azure门户中注册应用程序 - 登录Azure门户,进入Microsoft Entra ID(或Azure AD)。 - 创建新注册:提供名称,选择支持的账户类型(例如,仅限组织目录中的账户)。 - 注册后,记录应用程序(客户端)ID和目录(租户)ID。 - 在“证书和密码”部分,可以创建客户端密码(如果需要,例如守护程序场景)或上传证书。 - 在“重定向URI”中,添加应用程序登录后重定向的URI(例如:`https://localhost:44300/`,具体端口根据项目)。 ### 2. 创建项目并安装NuGet包 创建一个ASP.NET 4.8项目(例如MVC或Web Forms),然后通过NuGet安装以下包: - Microsoft.Owin.Host.SystemWeb - Microsoft.Owin.Security - Microsoft.Owin.Security.Cookies - Microsoft.Owin.Security.OpenIdConnect - Microsoft.IdentityModel.Protocols.OpenIdConnect ### 3. 配置Owin启动类 在项目中添加一个Owin启动类(通常命名为`Startup.cs`),并配置认证中间件。 ```csharp using Microsoft.Owin; using Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OpenIdConnect; using Microsoft.IdentityModel.Protocols; using System.Configuration; using System.Threading.Tasks; [assembly: OwinStartup(typeof(YourNamespace.Startup))] namespace YourNamespace { public class Startup { // 从配置文件中读取设置 private readonly string clientId = ConfigurationManager.AppSettings["ClientId"]; private readonly string tenantId = ConfigurationManager.AppSettings["TenantId"]; private readonly string redirectUri = ConfigurationManager.AppSettings["RedirectUri"]; private readonly string authority = "https://login.microsoftonline.com/{0}/v2.0"; public void Configuration(IAppBuilder app) { // 设置Cookie认证 app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); // 配置OpenID Connect认证 app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = string.Format(authority, tenantId), RedirectUri = redirectUri, PostLogoutRedirectUri = redirectUri, Scope = "openid email profile", // 根据需要添加其他范围 ResponseType = "id_token", // 隐式流返回id_token TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { // 验证令牌的颁发者 ValidIssuer = $"https://sts.windows.net/{tenantId}/" }, Notifications = new OpenIdConnectAuthenticationNotifications { AuthenticationFailed = context => { context.HandleResponse(); context.Response.Redirect("/Error?message=" + context.Exception.Message); return Task.FromResult(0); } } }); } } } ``` ### 4. 修改Web.config 在Web.config的`<appSettings>`中添加配置: ```xml <add key="ClientId" value="你的应用程序(客户端)ID" /> <add key="TenantId" value="你的目录(租户)ID" /> <add key="RedirectUri" value="https://localhost:44300/" /> ``` ### 5. 添加登录和注销功能 在需要的地方(例如在视图或控制器中)添加登录和注销的链接。 登录:可以触发挑战,例如在控制器中: ```csharp public void SignIn() { if (!Request.IsAuthenticated) { // 发送OpenID Connect登录请求 HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType); } } ``` 注销:同样在控制器中: ```csharp public void SignOut() { // 注销本地Cookie并重定向到Microsoft Entra ID注销端点 HttpContext.GetOwinContext().Authentication.SignOut( OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); } ``` ### 6. 授权 可以使用`[Authorize]`特性来保护控制器或方法。对于基于角色的授权,可以在Microsoft Entra ID中定义应用角色,并将用户分配给这些角色。然后在令牌中会返回角色声明,然后就可以使用`[Authorize(Roles="Admin")]`这样的特性。 注意:在传统ASP.NET中,需要将角色声明转换为ASP.NET能够识别的角色类型。可以在`Global.asax`的`Application_Start`中设置: ```csharp System.Web.Helpers.AntiForgeryConfig.UniqueClaimTypeIdentifier = "http://schemas.microsoft.com/identity/claims/objectidentifier"; ``` 然后在令牌验证时,将角色声明转换为`ClaimsIdentity`的角色声明。通常,在OpenID Connect中间件中,我们可以通过设置`TokenValidationParameters.RoleClaimType`来指定角色声明类型。 ### 注意事项 - 上述示例使用隐式流(返回id_token)进行用户登录。如果应用还需要访问其他API,可能需要使用授权码流(并添加`code`响应类型)以获取访问令牌。 - 在生产环境中,应使用HTTPS,并确保重定向URI已正确注册。 以上是在ASP.NET 4.8中集成Microsoft Entra ID进行身份验证的基本步骤。具体细节可能需要根据实际需求调整。 §§相关问题§§ 1. 在ASP.NET 4.8中集成Microsoft Entra ID时,如何处理角色授权? 2. 如何在Microsoft Entra ID中为应用程序配置应用角色? 3. 在ASP.NET 4.8中,如何获取用户的访问令牌以调用其他受保护的API? </think> ### 在 ASP.NET 4.8 中集成 Microsoft Entra ID 的步骤 #### 1. **在 Azure 门户注册应用程序** - 登录 [Azure 门户](https://portal.azure.com),进入 **Microsoft Entra ID**(原 Azure AD) - 选择 **应用注册** → **新注册** - 填写应用名称(如 `MyAspNetApp`),选择 **账户类型**(如 "仅此组织目录") - 设置 **重定向 URI**:选择 **Web** 类型,输入 `https://localhost:{端口}/signin-oidc`(端口需本地 IIS Express 一致) - 记录 **应用程序(客户端)ID** 和 **目录(租户)ID**[^3] #### 2. **配置项目 NuGet 包** 在 Visual Studio 中安装必要包: ```powershell Install-Package Microsoft.Owin.Security.OpenIdConnect Install-Package Microsoft.Owin.Security.Cookies Install-Package Microsoft.Owin.Host.SystemWeb ``` #### 3. **添加 OWIN 启动配置** 创建 `Startup.cs` 文件,配置认证中间件: ```csharp using Microsoft.Owin; using Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OpenIdConnect; [assembly: OwinStartup(typeof(MyNamespace.Startup))] namespace MyNamespace { public class Startup { public void Configuration(IAppBuilder app) { // Cookie 认证设置 app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); // OpenID Connect 配置 var clientId = "你的客户端ID"; var tenantId = "你的租户ID"; var authority = $"https://login.microsoftonline.com/{tenantId}/v2.0"; app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = authority, RedirectUri = "https://localhost:44300/", // 匹配 Azure 设置 PostLogoutRedirectUri = "https://localhost:44300/", Scope = "openid profile email", ResponseType = "id_token", TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuer = true, ValidIssuer = authority }, Notifications = new OpenIdConnectAuthenticationNotifications() }); } } } ``` #### 4. **保护路由** 在控制器或 Action 上添加 `[Authorize]` 特性: ```csharp [Authorize] public class SecureController : Controller { // 仅认证用户可访问 public ActionResult Index() { var userName = User.Identity.Name; return View(); } } ``` #### 5. **配置 Web.config** 添加以下配置节: ```xml <system.web> <authentication mode="None" /> <!-- 禁用传统认证 --> </system.web> <appSettings> <add key="ida:ClientId" value="你的客户端ID" /> <add key="ida:TenantId" value="你的租户ID" /> </appSettings> ``` #### 6. **处理登入/登出** 添加登录按钮(视图示例): ```html @if (!User.Identity.IsAuthenticated) { <a href="/Account/Login">使用 Microsoft Entra ID 登录</a> } else { <a href="/Account/Logout">注销</a> } ``` 控制器方法: ```csharp public class AccountController : Controller { public void Login() { if (!Request.IsAuthenticated) { HttpContext.GetOwinContext().Authentication.Challenge( new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType); } } public void Logout() { HttpContext.GetOwinContext().Authentication.SignOut( OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); } } ``` #### 7. **测试部署** - 本地测试:按 F5 启动调试,点击登录按钮应跳转至 Microsoft 登录页 - 生产部署: 1. 在 Azure 应用注册中更新 **重定向 URI**(如 `https://生产域名/signin-oidc`) 2. 发布项目到 IIS 服务器 3. 确保服务器时间 Azure 时间同步 > **注意**:ASP.NET 4.x 使用 OWIN 中间件集成, ASP.NET Core 的配置方式不同[^1][^2]。若需高级功能(如角色授权),需在 Azure 门户配置 **应用角色** 并在令牌中返回角色声明[^3]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值