ASP. NET Core 3.1 MVC AddOpenIDConnect с IdentityServer3 - PullRequest
0 голосов
/ 06 марта 2020

Любая помощь по этому вопросу будет принята с благодарностью. Я потратил несколько дней на это.

Аутентификация приложения ASP. NET Core 3.1 MVC с IdentityServer3 вызывает ошибку времени выполнения. Сервер идентификации возвращает ошибку

Клиентское приложение неизвестно или не авторизовано

вместо экрана входа в систему. У нас есть приложение ASP. NET MVC 5 и базовый API ASP. NET, который прекрасно работает с сервером идентификации.

Мой подход заключается в переписывании ASP . NET MVC 5 кодов. NET Core. Я сделал все, что мог, не имея возможности найти какую-либо документацию о том, как сделать такой перевод. Пожалуйста, смотрите мои фрагменты кода ниже для подробностей.

Рабочий ASP. NET MVC 5 код:

    //***
    //commented all code that was not needed to get login screen to show up
    //***
    public void Configuration(IAppBuilder app)
    {
        AntiForgeryConfig.UniqueClaimTypeIdentifier = IdentityModel.JwtClaimTypes.Name;
        JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Cookies",
            ExpireTimeSpan = new TimeSpan(0, 300, 0),
            SlidingExpiration = true
        });

        var clientBaseUrl = ConfigurationManager.AppSettings[ClientBaseUrlKey];
        var identityServerBaseUrl = ConfigurationManager.AppSettings[IdentityServerBaseUrlKey];

        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            Authority = identityServerBaseUrl,
            ClientId = WebSettings.ClientId,
            ResponseType = "code id_token token",
            SignInAsAuthenticationType = "Cookies",
            UseTokenLifetime = false//,
            RedirectUri = $"{clientBaseUrl}/",
            //PostLogoutRedirectUri = clientBaseUrl,
            //Scope = "openid profile roles admin_certpay",

            //Notifications = new OpenIdConnectAuthenticationNotifications
            //{

... удален для краткости ...}); }

Проблематично c ASP. NET Core 3.1 MVC код:

publi c void ConfigureServices (IServiceCollection services) {services.AddControllersWithViews ();

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            options.DefaultAuthenticateScheme = "Cookies";
        }).AddCookie("Cookies")
        .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, o =>
        {
            o.Authority = "http://localhost/identity/";
            o.ClientId = "actual value used here";
            o.ResponseType = "code id_token token"; 
            o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            o.UseTokenLifetime = false;
            //start - not sure what RedirectUri is, but PostLogoutRedirectUri doesn't matter
            o.SignedOutRedirectUri = "http://localhost/CertPay.Admin/";
            o.ReturnUrlParameter = "http://localhost/CertPay.Admin/";
            //end - not sure what RedirectUri is, but PostLogoutRedirectUri doesn't matter
            o.RequireHttpsMetadata = false; //fix to runtime error
        });

        //Played with Core API fix for the hell of it.
        //.AddIdentityServerAuthentication(o =>
        //{
        //    o.Authority = "http://localhost/identity/";
        //    //o.ApiName = "actual value here";
        //    o.LegacyAudienceValidation = true;
        //    o.RequireHttpsMetadata = true;
        //});
}

1 Ответ

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

Ответ, предоставленный Педро Малышом на этой теме , решил мою проблему. Удаление атрибута RedirectUri можно компенсировать, добавив прослушиватель событий. Для вашего удобства ниже приводится выдержка из Педро:

x.Events.OnRedirectToIdentityProvider = async n =>
{
    n.ProtocolMessage.RedirectUri = <Redirect URI string>;
    await Task.FromResult(0);
}

Редактировать: Фактическое решение, приведенное выше, вызвало бесконечную загрузку l oop страницы входа в систему несколько раз. Следующее решение не вызвало этой проблемы:

o.CallbackPath = "/home/index/";
...