Asp. NET 4.7.2 Несколько провайдеров аутентификации Owin - PullRequest
0 голосов
/ 17 апреля 2020

Можно ли использовать двух провайдеров OpenIdConnect в одном приложении? Мне нужно иметь логины для двух разных групп: первая - это сотрудники, у которых есть действительные учетные записи Azure AD, и вторые клиенты, у которых нет Azure учетных записей AD. Я знаю, какие конечные точки использовать, и работал с приложениями, которые содержат эту функциональность, используя. NET Core, но я не могу успешно реализовать это в. NET 4.7.2

В моем файле start.auth. Файл CS Я пытался добавить провайдеров, как это

app.UseOpenIdConnectAuthentication(CustomerOptions());
app.UseOpenIdConnectAuthentication(EmployeeOptions());

    private static OpenIdConnectAuthenticationOptions EmployeeOptions() =>
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = ClientId,
                Authority = authority,
                RedirectUri = RedirectUri,
                ClientSecret = ClientSecret,
                PostLogoutRedirectUri = RedirectUri,
                Scope = OpenIdConnectScope.OpenIdProfile,
                // ResponseType is set to request the id_token - which contains basic information about the signed-in user
                ResponseType = OpenIdConnectResponseType.CodeIdToken,
                // 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 // This is a simplification
                },
                // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = OnAuthenticationFailed,
                    SecurityTokenValidated = OnAdSecurityTokenValidated
                }
            };

Где ... Методы параметров имеют OpenIdConnectAuthenticationOptions, определяющих c для каждой конечной точки. Если я использую только один из методов, которые я могу аутентифицировать в приложении, но когда я пытаюсь добавить обе аутентификации, будет использоваться только тот клиент, который был добавлен последним.

Код, который вызывает методы: 1. вызывает Azure AD провайдер

            HttpContext.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties { RedirectUri = "/" },
                OpenIdConnectAuthenticationDefaults.AuthenticationType);

звонит провайдеру клиента

        var properties = new AuthenticationProperties { RedirectUri = "/" };
        var scheme = "schemeName";
        HttpContext.GetOwinContext().Authentication.Challenge(properties, scheme);

Как мне позвонить соответствующему провайдеру аутентификации?

Спасибо

Ответы [ 2 ]

1 голос
/ 20 апреля 2020

Вам необходимо установить разные схемы для каждого промежуточного ПО аутентификации через свойство OpenIdConnectAuthenticationOptions.AuthenticationType и передать схему, которую вы хотите аутентифицировать, методом Challenge(...).

0 голосов
/ 20 апреля 2020

Я пренебрег установкой параметра типа аутентификации при обновлении OpenIdConnectAuthenticationOptions, поэтому я перезаписывал настройки по умолчанию при добавлении второго поставщика аутентификации.

app.UseOpenIdConnectAuthentication(CustomerOptions());
app.UseOpenIdConnectAuthentication(EmployeeOptions());

private static OpenIdConnectAuthenticationOptions EmployeeOptions() =>
        new OpenIdConnectAuthenticationOptions("employeeAuthenticationType")
        {
            ClientId = ClientId,
            Authority = authority,
            RedirectUri = RedirectUri,
            ClientSecret = ClientSecret,
            PostLogoutRedirectUri = RedirectUri,
            Scope = OpenIdConnectScope.OpenIdProfile,
            // ResponseType is set to request the id_token - which contains basic information about the signed-in user
            ResponseType = OpenIdConnectResponseType.CodeIdToken,
            // 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 // This is a simplification
            },
            // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = OnAuthenticationFailed,
                SecurityTokenValidated = OnAdSecurityTokenValidated
            }
        };
...