使用 Owin OpenId Connect 认证授权的 Asp.net 4.8 WebForms(app.UseOpenIdConnectAuthentication)

4
我在login.microsoftonline.com和我的应用程序之间遇到了无限重定向循环。 我的项目正在在Asp.net 4.8 Web Forms项目中实现身份验证和授权。 我能够使用默认的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 config来完成此操作:

<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 响应,这导致了循环。

如何修改它,使未经授权(但已认证)的用户不是被重定向到 login.microsoftonline.com,而是应该被引导到一个应用程序页面,显示 401 错误?

2个回答

0
请检查以下解决方法是否有帮助:
通常情况下,如果启用了"表单身份验证",当状态码为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");
      }
      

您还可以查看此链接 > ASP .Net中将未经授权的用户重定向到消息页面。 (microsoft.com)

其他参考资料

  1. 防止状态代码401(未经授权)重定向到登录(microsoft.com)
  2. asp.net - 401未经授权的现场处理(无重定向)?- Stack Overflow

谢谢,@kavyasaraboju-MT,实际上我没有使用表单身份验证,而是使用OWIN中间件。我将更新上面的web.config片段以明确这一点。 - ToDevAndBeyond

0

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) => { ... }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接