簡體   English   中英

Asp.net 4.8 WebForms授權使用Owin OpenId Connect Authentication (app.UseOpenIdConnectAuthentication)

[英]Asp.net 4.8 WebForms authorization using Owin OpenId Connect Authentication (app.UseOpenIdConnectAuthentication)

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

如果用戶具有該角色,則向經過身份驗證的頁面添加授權可以正常工作,但如果沒有該角色的用戶嘗試訪問該頁面,他們將被重定向回 login.microsoftonline.com,然后無限期地返回到應用程序環形。

我可以看到 Owin UseOpenIdConnectAuthentication 在未經授權時返回 302 響應,這導致了循環。

我該如何更改它,而不是將未經授權(但經過身份驗證)的用戶重定向到 login.microsoftonline.com,而是應將該用戶定向到顯示 401 錯誤的應用程序頁面?

請檢查以下解決方法是否有幫助:

通常情況下,如果啟用了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");
      }
      

您還可以檢查此 > 將未經授權的用戶重定向到 ASP.Net 中的消息頁面。 (微軟網站)

其他參考資料

  1. 防止重定向登錄狀態代碼 401(未授權)(microsoft.com)
  2. asp.net - 未經授權的 401 就地處理(無重定向)? - 堆棧溢出

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="?" />覆蓋此行為 <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) => { ... }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM