Asp.net 4.8使用Owin OpenId连接身份验证的Web表单授权(应用程序UseOpenIdConnectAuthentication)

qkf9rpyu  于 2022-12-20  发布在  .NET
关注(0)|答案(2)|浏览(160)

我在www.example.com和应用程序之间遇到无限重定向循环login.microsoftonline.com。我的项目正在www.example.com 4.8 Web窗体项目中实现身份验证和授权Asp.net。我可以使用默认Owin启动文件添加身份验证,然后在Web配置文件中要求进行身份验证。要求用户在能够访问pages/AuthRequired之前登录时,下面的代码可以正常工作
StartupAuth.CS

public partial class Startup
    {
        private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
        private static string authority = ConfigurationManager.AppSettings["ida:Authority"];
        private static string clientSecret = ConfigurationManager.AppSettings["AppRegistrationSecret-Local"];
        public void ConfigureAuth(IAppBuilder app)
        {
            //for debugging
            //IdentityModelEventSource.ShowPII = true;

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = clientId,
                    Authority = authority,
                    PostLogoutRedirectUri = postLogoutRedirectUri,
                    ClientSecret = clientSecret,
                    RedirectUri = postLogoutRedirectUri,
                    //This allows multitenant
                    //https://github.com/Azure-Samples/guidance-identity-management-for-multitenant-apps/blob/master/docs/03-authentication.md
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = false
                    },

                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        AuthenticationFailed = (context) =>
                        {
                            return Task.FromResult(0);
                        }
                    }
                }
                );

            // This makes any middleware defined above this line run before the Authorization rule is applied in web.config
            app.UseStageMarker(PipelineStage.Authenticate);
        }
    }

Web.Config

<configuration>
...
    <system.web>
        <authentication mode="None" />
    </system.web>
    <location path="Pages/AuthRequired">
        <system.web>
            <authorization>
                <deny users="?" />
            </authorization>
        </system.web>
    </location>
    <system.webServer>
        <modules>
            <remove name="FormsAuthentication" />
        </modules>
    </system.webServer>
...
</configuration>

我需要添加授权,以便只有具有管理员角色的用户才能访问Pages/AuthRequired。我已通过更新Web配置完成此操作:

<configuration>
...
    <system.web>
        <authentication mode="None" />
    </system.web>
    <location path="Pages/AuthRequired">
        <system.web>
            <authorization>
                <allow roles="Admin" />
                <deny users="*" />
            </authorization>
        </system.web>
    </location>
    <system.webServer>
        <modules>
            <remove name="FormsAuthentication" />
        </modules>
    </system.webServer>
...
</configuration>

如果用户具有该角色,则向经过身份验证的页面添加授权可以正常工作,但如果不具有该角色的用户尝试访问该页面,则会在无限循环中将其重定向回login.microsoftonline.com,然后再重定向回应用程序。
我可以看到Owin UseOpenIdConnectAuthentication在未授权时返回302响应,这导致了循环。
如何更改它,使该用户被定向到显示401错误的应用程序页面,而不是将未经授权(但经过身份验证)的用户重定向到login.microsoftonline.com?

ffscu2ro

ffscu2ro1#

请检查以下变通方案是否有帮助:
通常情况下,如果启用了forms authentication,当状态代码为401时,您将被重定向到登录页面。
作为一种解决办法,尝试在应用程序结束请求中将以下内容添加到global.asax,如果需要,您可以创建自己的未授权页面并重定向到该页面。

if (this.Response.StatusCode == 302&& this.Response.StatusCode == 401 
        && this.Response.RedirectLocation.ToLower().Contains("login.aspx"))
      {
        this.Response.StatusCode = 401;
         //or Response.Redirect("Unauthorized.aspx");
      }

您也可以选中此〉Redirect unauthorised user to message page in ASP .Net. (microsoft.com)

其他参考资料

  1. Prevent redirect to login on status code 401 (Unauthorized) (microsoft.com)
  2. asp.net - In-place handling (no redirect) of 401 unauthorized? - Stack Overflow
gwo2fgha

gwo2fgha2#

ASP.NET URL授权似乎无法与OIDC(即Azure AD)很好地互操作。
首先从Web.config中删除URL授权:

<configuration>
...
    <system.web>
        <authentication mode="None" />
    </system.web>
    <location path="Pages/AuthRequired">
        <system.web>
--            <authorization>
--                <allow roles="Admin" />
--                <deny users="*" />
--            </authorization>
        </system.web>
    </location>
    <system.webServer>
        <modules>
            <remove name="FormsAuthentication" />
        </modules>
    </system.webServer>
...
</configuration>

选择性地使所有页面全局要求验证:

<system.web>
      <deny users="?" />
    </system.web>

您可以使用<Allow users="?" />覆盖特定页面(例如登录/注销/错误页面/等)的此行为。
其次,将授权逻辑添加到AuthRequired.aspx页面:

public partial class AuthRequired {
  protected void Page_Load(object sender, EventArgs e)
  {
    Authorization.AuthorizeAuthRequiredPage();
    ...
  }
}

public static class Authorization
{
  public static void AuthorizeAuthRequiredPage()
  {
    if (!Authorized(HttpContext.User))
    {
      Redirect("/Anauthorized.aspx");
    }
  }

  private static bool Authorized(User user) => { ... }
}

相关问题