【问题标题】:Asp.net 4.8 WebForms authorization using Owin OpenId Connect Authentication (app.UseOpenIdConnectAuthentication)Asp.net 4.8 WebForms授权使用Owin OpenId Connect Authentication (app.UseOpenIdConnectAuthentication)
【发布时间】:2022-12-17 00:33:39
【问题描述】:

我在 login.microsoftonline.com 和我的应用程序之间遇到无限重定向循环。我的项目是在 Asp.net 4.8 Web 窗体项目中实现身份验证和授权。我可以使用默认的 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);
        }
    }

网页配置

<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。我通过更新网络配置来做到这一点:

<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>

如果用户具有该角色,则向经过身份验证的页面添加授权可以正常工作,但如果没有该角色的用户尝试访问该页面,他们将被重定向回 l​​ogin.microsoftonline.com,然后无限期地返回到应用程序环形。

我可以看到 Owin UseOpenIdConnectAuthentication 在未经授权时返回 302 响应,这导致了循环。

我该如何更改它,而不是将未经授权(但经过身份验证)的用户重定向到 login.microsoftonline.com,而是应将该用户定向到显示 401 错误的应用程序页面?

【问题讨论】:

    标签: c# asp.net azure-active-directory owin


    【解决方案1】:

    请检查以下解决方法是否有帮助:

    如果启用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

    【讨论】:

    • 谢谢,@kavyasaraboju-MT,我实际上没有使用表单身份验证,而是使用了 OWIN 中间件。我将更新上面的 web.config sn-p 以明确说明
    【解决方案2】:

    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>
    

    您可以针对特定页面使用 &lt;Allow users="?" /&gt; 覆盖此行为,即登录/注销/错误页面/等。

    其次将授权逻辑添加到您的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) => { ... }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-04
      • 2018-12-19
      • 2021-10-18
      • 2019-09-11
      • 2017-05-05
      • 2023-03-05
      • 2020-01-09
      • 2019-02-24
      相关资源
      最近更新 更多