Azure AD Open ID Connect OAuth 2.0 в ASP. NET Веб-приложение и веб-API Бесконечный цикл перенаправления - PullRequest
0 голосов
/ 27 марта 2020

ASP. NET веб-приложение для входа в личные учетные записи, рабочие и школьные учетные записи из любого экземпляра Azure Active Directory (Azure AD).

Пакеты промежуточного ПО OWIN NuGet

Install-Package Microsoft.Owin.Security.OpenIdConnect
Install-Package Microsoft.Owin.Security.Cookies
Install-Package Microsoft.Owin.Host.SystemWeb

Класс запуска OWIN Промежуточное ПО OWIN использует класс запуска, который запускается при инициализации процесса хостинга. В этом быстром запуске файл startup.cs находится в папке root. В следующем коде показан параметр, используемый этим быстрым запуском

public void Configuration(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions());
    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            // Sets the ClientId, authority, RedirectUri as obtained from web.config
            ClientId = clientId,
            Authority = authority,
            RedirectUri = redirectUri,
            // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
            PostLogoutRedirectUri = redirectUri,
            Scope = OpenIdConnectScope.OpenIdProfile,
            // ResponseType is set to request the id_token - which contains basic information about the signed-in user
            ResponseType = OpenIdConnectResponseType.IdToken,
            // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
            // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
            // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = false // Simplification (see note below)
            },
            // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = OnAuthenticationFailed
            }
        }
    );
}

ASP. NET MVC / Web API

//You can force a user to sign in by requesting an authentication challenge in your controller:
public void SignIn()
{
    if (!Request.IsAuthenticated)
    {
        HttpContext.GetOwinContext().Authentication.Challenge(
            new AuthenticationProperties{ RedirectUri = "/" },
            OpenIdConnectAuthenticationDefaults.AuthenticationType);
    }
}

ASP. NET Веб-форма:

 protected void Login_click(object sender, EventArgs e)
        {
            if (!Request.IsAuthenticated)
            {
                HttpContext.Current.GetOwinContext().Authentication.Challenge(
                    new AuthenticationProperties { RedirectUri = "/" },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }
        }

1 Ответ

0 голосов
/ 27 марта 2020

Проблема была исправлена ​​в ядре ASP. NET и в новой версии Katana Owin для ASP. NET. Чтобы решить эту проблему, вы можете обновить приложение, чтобы использовать ASP. NET Core. Если вам по-прежнему нужно оставаться на ASP. NET, выполните следующее:

Обновите пакет Microsoft.Owin.Host.SystemWeb своего приложения как минимум до версии 3.1.0.0 и измените код, чтобы использовать один из следующих вариантов: новый менеджер ie менеджер классов, например что-то вроде следующего:

app.UseCookieAuthentication(new CookieAuthenticationOptions 
{ 
    AuthenticationType = "Cookies", 
    CookieManager = new Microsoft.Owin.Host.SystemWeb.SystemWebChunkingCookieManager() 
});
...