ASP.Net MVC 为使用应用程序网关的授权重定向设置自定义主机名

ASP.Net MVC Set custom hostname for authorization redirect with Application Gateway

场景:ASP.net Azure 应用程序网关后面的 MVC 应用程序

当未经授权的用户尝试访问控制器方法受 Authorize 属性保护的页面时,用户将被重定向到 Azure AD 登录页面。登录后,用户将被重定向到无法访问的应用程序 URL(给出 403),而不是正确的应用程序网关 URL。

当我们使用时,登录工作正常:

HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);

所以问题是:是否有一种好方法来覆盖 Authorize 属性正在使用的主机名,以便它重定向到应用程序网关 URL 即在应用程序设置中指定?

在 startup.auth.cs 内部,我们使用 OpenId Connect 并将重定向 URI 设置为正确的应用程序网关 URL,这可用于成功验证,但仍会重定向到不正确的 URL用户通过身份验证后。

 Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = (context) =>
                    {
                        string appBaseUrl = _siteUrl;
                        context.ProtocolMessage.RedirectUri = appBaseUrl;

从以下问题中找到我自己的答案:

总而言之,可以通过在 A​​uthorizationCodeReceived 回调[=12] 中设置 context.AuthenticationTicket.Properties.RedirectUri 来实现身份验证后的重定向=]

         app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {


                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = (context) =>
                    {

                        _redirectUri = _siteUrl + context.Request.Path;


                        return Task.FromResult(0);
                    },
                    // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                    AuthorizationCodeReceived = async (context) =>
                    {
                        var httpContext =
                            HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as
                                HttpContextBase;
                        var code = context.Code;
                        context.AuthenticationTicket.Properties.RedirectUri = _redirectUri;


                       }
                    },
                    AuthenticationFailed = OnAuthenticationFailed
                }
            });