在 Asp.NET Core Azure AD 身份验证中配置重定向 URI

piz*_*cki 6 .net azure-active-directory asp.net-core blazor

如何告诉我的应用程序使用我提供的主机生成重定向 URI?( foobar.com)

语境:

我有服务器端 Blazor Web 应用程序,从最近的 (VS 16.7.5) 模板生成,具有 Azure AD(单租户、工作和学校)身份验证。

我用 <PackageReference Include="Microsoft.AspNetCore.Authentication.AzureAD.UI" Version="3.1.8" />

我已在 Az Portal 等处配置了接受的重定向 URL,并且可以在本地运行我的应用程序时使用 Azure AD 登录。

流动

重定向 URI 在重定向到 Azure AD 站点时在查询参数中发送,它指向实际上是 的网站主机foobar.azurewebsites.net

如何告诉我的应用程序使用我提供的主机生成重定向 URI?( foobar.com)

我发现的唯一解决方案与以前的 ASP.NET 相关。

<add key="ida:RedirectUri" value="https://localhost:44326/" />

这对我来说不起作用。

Ro *_*Hit 4

当Web应用程序位于Azure前门或应用程序网关后面时,我们需要将/authorize请求中的redirect_uri配置为网关/前门的地址。

\n

在下面的代码中,我们重写“OnRedirectToIdentityProvider”事件并注入前门/网关的地址。当我尝试这个时,我只是对地址进行了硬编码,但理想情况下,您可以从 Front Door 或应用程序网关注入到请求中的标头中提取它。

\n

这是我在尝试对在 Azure 应用服务上运行的 Blazor 服务器应用程序 (.net 5) 进行身份验证时使用的代码,该服务受 Azure AD 保护,在 Azure Front Door 后面运行。

\n
public void ConfigureServices(IServiceCollection services)\n{\n    // ... existing code\n\n    services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)\n                .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))\n                .EnableTokenAcquisitionToCallDownstreamApi(new[] { "User.Read" })\n                .AddInMemoryTokenCaches();\n\n    services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>\n    {\n        options.Events = new OpenIdConnectEvents\n        {\n            OnRedirectToIdentityProvider = (context) =>\n            {   \n                // Override the redirect_uri\n                //  Ideally extract this from config \n                //  Or context.Request.Headers["X-Forwarded-Host"]\n                //  see: https://learn.microsoft.com/en-us/azure/frontdoor/front-door-http-headers-protocol#front-door-to-backend\n\n                context.ProtocolMessage.RedirectUri \n                    = "https://YOUR-FRONT-DOOR-or-APP-GATEWAY/signin-oidc";\n                return Task.FromResult(0);\n            }\n        };\n    });\n\n    services.Configure<ForwardedHeadersOptions>(options =>\n    {\n        options.ForwardedHeaders = ForwardedHeaders.XForwardedFor |\n                        ForwardedHeaders.XForwardedProto;\n        options.KnownNetworks.Clear();\n        options.KnownProxies.Clear();\n    });\n\n    // ... existing code\n}\n\npublic void Configure(IApplicationBuilder app, IWebHostEnvironment env)\n{\n    // ... existing code\n    \n    // Don\'t forget to add this ...\n    app.UseForwardedHeaders();\n    \n    // ... existing code\n}\n
Run Code Online (Sandbox Code Playgroud)\n

当代码运行时,“redirect_uri”参数应指向您的前门/网关,如下所示。

\n

OAuth 流程

\n

希望有帮助。\xe2\x9d\xa4\xef\xb8\x8f

\n