ASP.NET Core OpenID Connect 示例实战:在 OpenIdConnectSample 中配置 Azure AD 与 Google 身份提供方

发布时间:2026/9/10 4:28:23
ASP.NET Core OpenID Connect 示例实战:在 OpenIdConnectSample 中配置 Azure AD 与 Google 身份提供方 ASP.NET Core OpenID Connect 示例实战在 OpenIdConnectSample 中配置 Azure AD 与 Google 身份提供方【免费下载链接】aspnetcoreASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.项目地址: https://gitcode.com/GitHub_Trending/as/aspnetcore本指南以 aspnetcore 仓库中的 OpenIdConnectSample 示例文档 为核心完整讲解如何在本地把该示例跑起来并分别用 Azure Active Directory 与 Google Identity Platform 作为 OpenID Connect 授权服务器完成登录配置。读完本文你将掌握 OpenID Connect 认证的完整配置流程授权服务器侧的应用注册、示例侧的用户机密user secrets设置、AddOpenIdConnect()的核心选项含义以及示例内置的登录、登出、令牌刷新与 Claim 映射机制。示例概述一个支持多身份提供方的 OpenID Connect 客户端OpenIdConnectSample是 ASP.NET Core 官方的 OpenID Connect 交互式客户端示例位于 src/Security/Authentication/OpenIdConnect/samples/OpenIdConnectSample其文档明确说明The OpenIdConnect sample supports multiple authentication providers.也就是说示例本身不绑定某一特定厂商只要身份提供方实现了 OpenID Connect 协议就可以接入。官方文档以Azure Active Directory和Google Identity Platform两条路线为例演示了从“在授权服务器注册应用”到“在示例中写入客户端凭据”的完整链路。示例目录结构如下OpenIdConnectSample/ ├── Properties/ │ └── launchSettings.json # Visual Studio 下的启动配置端口、环境变量 ├── OpenIdConnectSample.csproj ├── Program.cs # 命令行运行时承载宿主与启动类 ├── Readme.md # 本文依据的官方配置文档 └── Startup.cs # 认证管线与 OpenID Connect 选项的核心实现仓库中还提供了另一个精简版 MinimalOpenIdConnectSample仅用几行代码即可展示 OpenID Connect 认证的最小形态后文会对照讲解。确定本地开发环境与关键变量本地端口44318示例被配置为在本地44318端口运行这一设置取决于运行方式从 Visual Studio 运行端口配置在 Properties/launchSettings.json 中。实际内容显示OpenIdConnectSample与IIS Express两个 profile 都设置了applicationUrl: https://localhost:44318/并预置了ASPNETCORE_ENVIRONMENT: Development{ iisSettings: { windowsAuthentication: false, anonymousAuthentication: true, iisExpress: { applicationUrl: https://localhost:44318/, sslPort: 44318 } }, profiles: { OpenIdConnectSample: { commandName: Project, launchBrowser: true, environmentVariables: { ASPNETCORE_ENVIRONMENT: Development }, applicationUrl: https://localhost:44318/ }, IIS Express: { commandName: IISExpress, launchBrowser: true, environmentVariables: { ASPNETCORE_ENVIRONMENT: Development } } } }从命令行 / 终端运行此时端口与 URL 由 Program.cs 承载的宿主决定。示例的Program.cs使用Host.CreateDefaultBuilder(args)配合ConfigureWebHostDefaults与UseStartupStartup()启动应用public static Task Main(string[] args) { var host Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webHostBuilder { webHostBuilder .UseStartupStartup(); }) .Build(); return host.RunAsync(); }环境变量ASPNETCORE_ENVIRONMENT文档特别强调如果应用从命令行或终端运行必须将环境变量ASPNETCORE_ENVIRONMENT设置为DEVELOPMENT才能启用 user secrets用户机密功能。原因在于 .NET 的配置体系CreateDefaultBuilder只有在环境为 Development 时才会加载用户机密存储。示例项目在 OpenIdConnectSample.csproj 中声明了机密 IDUserSecretsIdaspnet5-OpenIdConnectSample-20151210110318/UserSecretsId这个 ID 是密钥在本地用户机密存储中的定位标识配合环境变量后dotnet user-secrets写入的值才能被IConfiguration以oidc:clientid这样的键名读取。配置授权服务器Azure Active Directory 路线文档给出了完整的 Azure AD 配置步骤按序执行即可在你的 Azure 订阅中创建一个新的 Azure Active DirectoryAAD。在 Azure 门户中打开新建的 AAD。进入App registrations应用注册选项卡。向 AAD 添加新应用将Sign-on URL登录 URL设置为示例应用的 URL即https://localhost:44318/。进入该应用点击Configure配置选项卡。找到并保存Client Id客户端 ID。在Keys密钥区域添加一个新密钥保存密钥值——这就是Client Secret客户端机密。点击抽屉drawer中的View Endpoints查看终结点弹出的对话框会显示六个终结点 URL。复制OAuth 2.0 Authorization Endpoint并去掉字符串末尾的/oauth2/authorize剩余部分即为authority URL形如https://login.microsoftonline.com/guid。进入Authentication选项卡在Implicit grant隐式授权下勾选启用ID tokens选项。仍在 Authentication 选项卡中确保Redirect URIs重定向 URI设置为https://localhost:44318/signin-oidc即示例应用 URI 追加/signin-oidc。其中两个关键点的含义需要明确authority URL是 OpenID Connect 发现的入口客户端据此获取授权、令牌、用户信息等所有协议端点。Azure 的 authority 形如https://login.microsoftonline.com/guidguid是你的 AAD 租户 ID。/signin-oidc是回跳路径授权服务器完成用户登录后会把授权码authorization code重定向回https://localhost:44318/signin-oidc由 OpenID Connect 处理器在服务端兑换令牌。这与后面Startup.cs中的认证方案名OpenIdConnect以及 handler 默认的回跳约定是对应的。配置授权服务器Google Identity Platform 路线如果选用 Google 作为身份提供方按以下步骤配置通过 Google Cloud 的 APIs ServicesGoogle APIs 控制台创建一个新项目。在侧边栏选择Credentials凭据。进入OAuth consent screenOAuth 同意屏幕选项卡填写项目名称并保存。进入Credentials凭据选项卡点击Create credentials创建凭据选择OAuth client IDOAuth 客户端 ID。应用类型选择Web applicationWeb 应用在Authorized redirect URIs已授权的重定向 URI中填写https://localhost:44318/signin-oidc。保存对话框中显示的Client ID和Client Secret。Google 认证的Authority URL为https://accounts.google.com/。与 Azure AD 相比Google 的 authority 是一个固定的域名而不是按租户动态生成的地址。其余协议行为发现文档、授权端点、令牌端点由 OpenID Connect 标准统一约定。配置示例应用授权服务器侧注册完成后回到示例应用完成本地配置第 1 步还原应用在示例目录下执行依赖还原将仓库中声明的框架引用恢复为可用的程序集dotnet restore第 2 步设置用户机密使用dotnet user-secrets把三个核心配置写入本地机密存储需先确认ASPNETCORE_ENVIRONMENT为 Developmentdotnet user-secrets set oidc:clientid Client Id dotnet user-secrets set oidc:clientsecret Client Secret dotnet user-secrets set oidc:authority Authority URL三个键的含义分别是机密键对应 OpenID Connect 选项说明oidc:clientidClientId授权服务器签发的客户端 IDoidc:clientsecretClientSecret客户端机密用于 authorization code 流程换令牌oidc:authorityAuthority授权服务器发现地址如 Azure 的https://login.microsoftonline.com/guid或 Google 的https://accounts.google.com/第 3 步让 AddOpenIdConnect 读取机密文档要求更新ConfigureServices中的AddOpenIdConnect()调用使其使用来自用户机密的配置值。示例的 Startup.cs 中预留了对应的代码骨架.AddOpenIdConnect(o { /* o.ClientId Configuration[oidc:clientid]; o.ClientSecret Configuration[oidc:clientsecret]; // for code flow o.Authority Configuration[oidc:authority]; */ ... });把注释块取消注释即完成“机密 → 配置 → 认证选项”的接线dotnet user-secrets set写入的值通过IConfiguration的oidc:xxx键被读取再赋给OpenIdConnectOptions的对应属性。源码深度解读Startup.cs 中的认证管线理解了“怎么配置”再看“为什么这样配置”。示例的 Startup.cs 完整展示了 ASP.NET Core 中 OpenID Connect 认证的经典管线可作为自己项目的最小可运行参照。认证方案与 Cookie 会话ConfigureServices中先配置了认证方案的选择策略services.AddAuthentication(sharedOptions { sharedOptions.DefaultScheme CookieAuthenticationDefaults.AuthenticationScheme; sharedOptions.DefaultChallengeScheme OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie() .AddOpenIdConnect(o { ... });DefaultScheme 是 Cookie用户成功登录后身份以 Cookie 会话的形式保存在浏览器端后续请求无需再与授权服务器交互。DefaultChallengeScheme 是 OpenIdConnect当未认证用户访问受保护资源时会触发 OpenID Connect 挑战浏览器被重定向到授权服务器登录页。方案名OpenIdConnect是约定值定义在 OpenIdConnectDefaults.cs 中public const string AuthenticationScheme OpenIdConnect;同文件还定义了CookieNoncePrefix .AspNetCore.OpenIdConnect.Nonce.用于在 Cookie 中保存 nonce、RedirectUriForCodePropertiesKey等协议内部键这些常量正是 handler 在协议往返中保持状态的基础。AddOpenIdConnect 的核心选项示例启用的选项及其含义如下o.ClientId interactive.confidential; o.ClientSecret secret; // for code flow o.Authority https://demo.duendesoftware.com/; o.ResponseType OpenIdConnectResponseType.Code; o.SaveTokens true; o.GetClaimsFromUserInfoEndpoint true; o.AccessDeniedPath /access-denied-from-remote; // o.MapInboundClaims false; o.ClaimsIssuer MyCustomIssuer;选项值作用ResponseTypeCode使用 authorization code 流程需要 ClientSecret 换令牌而非隐式流程SaveTokenstrue将 access_token、refresh_token 等令牌保存进AuthenticationProperties供后续刷新或调用受保护 API 使用GetClaimsFromUserInfoEndpointtrue认证完成后调用 UserInfo 端点获取附加声明再合并进 ClaimsIdentityAccessDeniedPath/access-denied-from-remote授权服务器返回 access_denied 时本地跳转的路径MapInboundClaimsfalse注释掉若启用将协议声明如sub映射为 .NET 的ClaimTypes命名示例默认保留原始协议声明ClaimsIssuerMyCustomIssuer为生成的声明指定自定义签发者覆盖默认的 authority 签发者注意示例代码默认使用的是 Duende 的演示授权服务器https://demo.duendesoftware.com/这部分是源码中便于“开箱即跑”的占位配置按 Readme 文档流程接入 Azure AD / Google 时应改用用户机密中的ClientId、ClientSecret、Authority。声明映射IssuerFixupAction 示例示例还演示了自定义声明处理o.ClaimActions.Add(new IssuerFixupAction());IssuerFixupAction继承自ClaimActionMicrosoft.AspNetCore.Authentication.OAuth.Claims命名空间在Run方法中遍历ClaimsIdentity的全部声明移除后以自定义 issuer 重建。这展示了ClaimActions扩展点在 OpenID Connect 管线中的位置令牌与 UserInfo 响应中的 JSON 数据会经过声明的映射与加工最终成为HttpContext.User上的ClaimsPrincipal。认证失败事件与 SameSite 兼容o.Events new OpenIdConnectEvents() { OnAuthenticationFailed c { c.HandleResponse(); c.Response.StatusCode 500; c.Response.ContentType text/plain; if (Environment.IsDevelopment()) { // Debug only, in production do not share exceptions with the remote host. return c.Response.WriteAsync(c.Exception.ToString()); } return c.Response.WriteAsync(An error occurred processing your authentication.); } };OnAuthenticationFailed事件在令牌校验等环节抛异常时触发开发环境下把异常详情写回响应便于排查生产环境只返回通用错误避免向远程主机泄露内部信息。示例同时实现了CheckSameSite与DisallowsSameSiteNone方法用于处理旧浏览器不支持SameSiteNone的兼容问题对 iOS 12 系列浏览器、macOS 上使用系统网络栈的 Safari、以及 Chrome 50-69 等 User-Agent将 Cookie 的 SameSite 降级为Unspecified。这与ConfigureServices开头的CookiePolicyOptionsMinimumSameSitePolicy SameSiteMode.Unspecified配合保证跨站重定向场景下认证 Cookie 仍能正常工作。中间件顺序与内置端点Configure中的中间件顺序是认证应用的标准模板app.UseDeveloperExceptionPage(); app.UseCookiePolicy(); // Before UseAuthentication or anything else that writes cookies. app.UseAuthentication();UseCookiePolicy必须先于UseAuthentication以及任何写 Cookie 的操作。随后的app.Run(...)内联实现了若干演示端点路径行为/未认证则ChallengeAsync()跳转登录已认证则渲染 Claims 与 Tokens 表格/restricted无specialtrue声明的用户触发ForbidAsync()演示基于声明的授权/refresh读取refresh_token向令牌端点发起刷新请求并更新保存的令牌/login-challenge以OpenIdConnectChallengeProperties携带Prompt login重新挑战强制用户重新输入凭据/signout清除本地 Cookie 会话/signout-remote同时调用SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme)向授权服务器发起端会话登出随后跳转/signedout/access-denied-from-remote展示授权服务器返回的 access_denied 错误页其中/refresh的实现揭示了令牌刷新的底层机制从props.GetTokenValue(refresh_token)取出刷新令牌通过options.ConfigurationManager.GetConfigurationAsync获取发现文档拿到TokenEndpoint再用options.Backchannel以表单形式 POSTclient_id、client_secret、grant_typerefresh_token、refresh_token最后把响应的新令牌写回AuthenticationProperties并重新SignInAsync。对照最小示例理解认证的最小骨架仓库中的 MinimalOpenIdConnectSample 用极简代码展示了同样的认证骨架builder.Services .AddAuthentication(OpenIdConnect) .AddCookie() .AddOpenIdConnect(); builder.Services.AddAuthorization(); var app builder.Build(); app.MapGet(/protected, (ClaimsPrincipal user) $Hello {user.Identity?.Name}!) .RequireAuthorization(); app.Run();两者对比可以看出AddAuthentication().AddCookie().AddOpenIdConnect()三行是任何 OpenID Connect 应用的标配完整示例额外演示的选项配置、事件处理、令牌刷新与声明映射都是在最小骨架上按需叠加的能力。实战中注册授权服务器、设置机密、配置ClientId/ClientSecret/Authority三步是不可或缺的最小闭环。验证与排错要点完成上述配置后从 Visual Studio 或命令行记得设置ASPNETCORE_ENVIRONMENTDevelopment启动应用访问https://localhost:44318/应观察到未登录时自动跳转到授权服务器Azure 登录页或 Google 登录页登录成功后跳回https://localhost:44318/signin-oidc页面显示 Hello 消息、Claims 与 Tokens 表格点击 Refresh tokens、Restricted、Sign Out Remote 等链接可验证令牌刷新、声明授权与端会话登出。常见排查方向重定向 URI 不匹配Azure 的 Redirect URIs 与 Google 的 Authorized redirect URIs 必须精确等于https://localhost:44318/signin-oidc含端口与路径机密未生效命令行运行时确认ASPNETCORE_ENVIRONMENTDevelopment否则用户机密不会被加载authority 拼写错误Azure 的 authority 末尾去掉/oauth2/authorize后应形如https://login.microsoftonline.com/guidGoogle 固定为https://accounts.google.com/认证失败开发环境下OnAuthenticationFailed事件会把异常详情写回响应可直接据此定位协议错误。结语OpenIdConnectSample 是理解 ASP.NET Core OpenID Connect 集成的绝佳起点它一端连接真实的授权服务器Azure AD 或 Google一端展示了客户端认证管线的全部关键环节——方案选择、选项配置、事件处理、令牌刷新与声明映射。按本指南完成注册与配置后你就可以把同样的模式迁移到自己的业务应用中。【免费下载链接】aspnetcoreASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.项目地址: https://gitcode.com/GitHub_Trending/as/aspnetcore创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考