简体   繁体   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)

I am encountering an infinite redirect loop between login.microsoftonline.com and my application.我在 login.microsoftonline.com 和我的应用程序之间遇到无限重定向循环。 My project is implementing authentication and authorization in an Asp.net 4.8 web forms project.我的项目是在 Asp.net 4.8 Web 窗体项目中实现身份验证和授权。 I am able to add authentication using the default Owin startup file and then require authentication in the web config file.我可以使用默认的 Owin 启动文件添加身份验证,然后在 Web 配置文件中要求身份验证。 The below works correctly for requiring a user to sign in before being able to access pages/AuthRequired以下内容可以正常工作,要求用户在能够访问pages/AuthRequired之前先登录

StartupAuth.CS 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>

I need to add authorization so that only users with the admin role will be able to access Pages/AuthRequired .我需要添加授权,以便只有具有管理员角色的用户才能访问Pages/AuthRequired I have done that by updating the 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>

Adding authorization to the authenticated page works correctly if the user has that role, but if a user who doesn't have the role tries to access the page they are redirected back to login.microsoftonline.com and then back to the application in an infinite loop.如果用户具有该角色,则向经过身份验证的页面添加授权可以正常工作,但如果没有该角色的用户尝试访问该页面,他们将被重定向回 login.microsoftonline.com,然后无限期地返回到应用程序环形。

I can see that Owin UseOpenIdConnectAuthentication is returning a 302 response on unauthorized and that is causing the loop.我可以看到 Owin UseOpenIdConnectAuthentication 在未经授权时返回 302 响应,这导致了循环。

How can I change it so that instead of redirecting unauthorized (but authenticated) users to login.microsoftonline.com, that user should be directed to an app page that displays a 401 error?我该如何更改它,而不是将未经授权(但经过身份验证)的用户重定向到 login.microsoftonline.com,而是应将该用户定向到显示 401 错误的应用程序页面?

Please check if below work around helps:请检查以下解决方法是否有帮助:

Its usually possible that if forms authentication is enabled, you will be redirected to the login page when status code is 401.通常情况下,如果启用了forms authentication ,当状态代码为 401 时,您将被重定向到登录页面。

As a workaround try Adding the below to global.asax in the application end request and you can create own unauthorized page if needed and redirect to that.作为一种解决方法,请尝试在应用程序结束请求中将以下内容添加到 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");
      }
      

You can also check this > Redirect unauthorised user to message page in ASP.Net.您还可以检查此 > 将未经授权的用户重定向到 ASP.Net 中的消息页面。 (microsoft.com) (微软网站)

Other references其他参考资料

  1. Prevent redirect to login on status code 401 (Unauthorized) (microsoft.com) 防止重定向登录状态代码 401(未授权)(microsoft.com)
  2. asp.net - In-place handling (no redirect) of 401 unauthorized? asp.net - 未经授权的 401 就地处理(无重定向)? - Stack Overflow - 堆栈溢出

ASP.NET URL Authorization doesn't appear to interoperate well with OIDC (ie Azure AD). ASP.NET URL 授权似乎无法与 OIDC(即 Azure AD)很好地互操作。

First remove the URL Authorization from your Web.config:首先从您的 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>

Optionally make authenticated required for all pages globally:可选地使全局所有页面都需要经过身份验证:

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

You can override this behaviour with <Allow users="?" />您可以使用<Allow users="?" />覆盖此行为<Allow users="?" /> for specific pages ie logins/logouts/erorr pages/etc. <Allow users="?" />用于特定页面,即登录/注销/错误页面/等。

Second add authorization logic to your AuthRequired.aspx page:其次将授权逻辑添加到您的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.

相关问题 ASP.NET OWIN OpenID Connect 未创建用户身份验证 - ASP.NET OWIN OpenID Connect not creating user authentication ASP.NET 使用外部 OpenID Connect 提供程序进行核心认证/授权 - ASP.NET Core authentication/authorization with external OpenID Connect provider ASP.NET Framework 4.8 / 4.7 通过 OpenId Connect 与外部 SSO 连接,授权代码授予流程,在 /signin-oidc 上返回 404 - ASP.NET Framework 4.8 / 4.7 connected with external SSO by OpenId Connect with Authorization Code Grant flow, returns 404 on /signin-oidc 如何从 ASP.Net OpenID Connect OWIN 组件设置声明? - How to set Claims from ASP.Net OpenID Connect OWIN components? 在ASP.NET WebForms中将OAuth与令牌一起使用Azure身份验证不是MVC - Azure Authentication using OAuth with token in ASP.NET WebForms NOT MVC 使用Owin中间件进行Active Directory身份验证的ASP.Net MVC - ASP.Net MVC with Active Directory Authentication using Owin Middleware 在 ASP.net Web API 中发生授权之前尝试使用 OWIN 注入授权标头 - Trying to inject Authorization header using OWIN before authorization happens in ASP.net Web API Google身份验证OWIN ASP.NET - Google Authentication OWIN ASP.NET ASP.NET Web API 和 OpenID Connect:如何从授权码获取访问令牌 - ASP.NET Web API and OpenID Connect: how to get Access Token from Authorization Code 如果在 ASP.NET (webforms) / OWIN 中多次单击,则复制用户 - Duplicating users if clicking multiple times in ASP.NET (webforms) / OWIN
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM