IdentityServer4 + Blazor - PullRequest
       4

IdentityServer4 + Blazor

1 голос
/ 15 января 2020

Я пытаюсь создать небольшую микросервисную архитектуру с: - службой IdentityServer 4 - аппликативной службой API - веб-приложением как другой службой

Мой код клиента в основном основан на @ McGuireV10 код здесь: https://mcguirev10.com/2019/12/15/blazor-authentication-with-openid-connect.html

Проблема в том, что у меня возникла проблема, и я не могу найти способ ее исправить:

System.Security.Cryptography.CryptographicException: 'The payload was invalid.'

с помощью этой трассировки стека :

Microsoft.AspNetCore.DataProtection.dll!Microsoft.AspNetCore.DataProtection.Cng.CbcAuthenticatedEncryptor.DecryptImpl(byte* pbCiphertext, uint cbCiphertext, byte* pbAdditionalAuthenticatedData, uint cbAdditionalAuthenticatedData)   Unknown
    Microsoft.AspNetCore.DataProtection.dll!Microsoft.AspNetCore.DataProtection.Cng.Internal.CngAuthenticatedEncryptorBase.Decrypt(System.ArraySegment<byte> ciphertext, System.ArraySegment<byte> additionalAuthenticatedData) Unknown
    Microsoft.AspNetCore.DataProtection.dll!Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(byte[] protectedData, bool allowOperationsOnRevokedKeys, out Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectStatus status)  Unknown
    Microsoft.AspNetCore.DataProtection.dll!Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(byte[] protectedData, bool ignoreRevocationErrors, out bool requiresMigration, out bool wasRevoked)  Unknown
    Microsoft.AspNetCore.DataProtection.dll!Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(byte[] protectedData) Unknown
    Microsoft.AspNetCore.Authentication.dll!Microsoft.AspNetCore.Authentication.SecureDataFormat<Microsoft.AspNetCore.Authentication.AuthenticationTicket>.Unprotect(string protectedText, string purpose)  Unknown
    Microsoft.AspNetCore.Authentication.Cookies.dll!Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler.ReadCookieTicket()  Unknown
    Microsoft.AspNetCore.Authentication.Cookies.dll!Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler.HandleAuthenticateAsync()   Unknown
    Microsoft.AspNetCore.Authentication.dll!Microsoft.AspNetCore.Authentication.AuthenticationHandler<Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationOptions>.AuthenticateAsync()  Unknown
    Microsoft.AspNetCore.Authentication.Core.dll!Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(Microsoft.AspNetCore.Http.HttpContext context, string scheme)  Unknown
    Microsoft.AspNetCore.Authentication.Abstractions.dll!Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.AuthenticateAsync(Microsoft.AspNetCore.Http.HttpContext context, string scheme)    Unknown
    Microsoft.AspNetCore.Authentication.dll!Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext context)  Unknown
    Microsoft.AspNetCore.Routing.dll!Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.SetRoutingAndContinue(Microsoft.AspNetCore.Http.HttpContext httpContext)    Unknown
    Microsoft.AspNetCore.Routing.dll!Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext httpContext)   Unknown
    Microsoft.AspNetCore.StaticFiles.dll!Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext context)    Unknown
    Microsoft.AspNetCore.StaticFiles.dll!Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext context)    Unknown
    Microsoft.AspNetCore.StaticFiles.dll!Microsoft.AspNetCore.StaticFiles.DefaultFilesMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext context)  Unknown
    Microsoft.AspNetCore.HttpsPolicy.dll!Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext context)  Unknown
    Microsoft.AspNetCore.Diagnostics.dll!Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext context)    Unknown
    Volo.Abp.AspNetCore.dll!Volo.Abp.AspNetCore.Tracing.AbpCorrelationIdMiddleware.InvokeAsync(Microsoft.AspNetCore.Http.HttpContext context, Microsoft.AspNetCore.Http.RequestDelegate next)   Unknown
    Microsoft.AspNetCore.Http.Abstractions.dll!Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.UseMiddlewareInterface.AnonymousMethod__1(Microsoft.AspNetCore.Http.HttpContext context)    Unknown
    Microsoft.AspNetCore.HostFiltering.dll!Microsoft.AspNetCore.HostFiltering.HostFilteringMiddleware.Invoke(Microsoft.AspNetCore.Http.HttpContext context) Unknown
    Microsoft.AspNetCore.Hosting.dll!Microsoft.AspNetCore.Hosting.HostingApplication.ProcessRequestAsync(Microsoft.AspNetCore.Hosting.HostingApplication.Context context)   Unknown
    Microsoft.AspNetCore.Server.IIS.dll!Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT<Microsoft.AspNetCore.Hosting.HostingApplication.Context>.ProcessRequestAsync()   Unknown
    Microsoft.AspNetCore.Server.IIS.dll!Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.HandleRequest() Unknown
    Microsoft.AspNetCore.Server.IIS.dll!Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.Execute()   Unknown

Вот обзор служб приложений.

enter image description here

Итак, с одной стороны, я начал идентификацию сервер с этим кодом запуска:

    context.Services.AddAuthentication(options =>
                {
                    options.DefaultScheme = "Cookies";
                    options.DefaultChallengeScheme = "oidc";
                })
                .AddCookie("Cookies", options =>
                {
                    options.ExpireTimeSpan = TimeSpan.FromDays(365);
                })
                .AddOpenIdConnect("oidc", options =>
                {
                    options.Authority = configuration["App:SelfUrl"];//configuration["AuthServer:Authority"];
                    options.RequireHttpsMetadata = true;
                    options.ResponseType = OpenIdConnectResponseType.CodeIdToken;

                    options.ClientId = configuration["AuthServer:ClientId"];
                    options.ClientSecret = configuration["AuthServer:ClientSecret"];

                    options.SaveTokens = true;
                    options.GetClaimsFromUserInfoEndpoint = true;

                    options.Scope.Add("role");
                    options.Scope.Add("email");
                    options.Scope.Add("phone");
                    options.Scope.Add("ProductFly");

                    options.ClaimActions.MapAbpClaimTypes();

                    options.Events = new Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectEvents
                    {
                        // called if user clicks Cancel during login
                        OnAccessDenied = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/");
                            return System.Threading.Tasks.Task.CompletedTask;
                        }
                    };
                });

Затем код запуска веб-приложения:

            context.Services.AddAuthentication(options =>
                {
                    options.DefaultScheme = "Cookies";
                    options.DefaultChallengeScheme = "oidc";
                })
                .AddCookie("Cookies", options =>
                {
                    options.ExpireTimeSpan = TimeSpan.FromDays(365);
                })
                .AddOpenIdConnect("oidc", options =>
                {
                    options.Authority = configuration["AuthServer:Authority"];
                    options.RequireHttpsMetadata = true;
                    options.ResponseType = OpenIdConnectResponseType.CodeIdToken;

                    options.ClientId = configuration["AuthServer:ClientId"];
                    options.ClientSecret = configuration["AuthServer:ClientSecret"];

                    options.SaveTokens = true;
                    options.GetClaimsFromUserInfoEndpoint = true;

                    options.Scope.Add("role");
                    options.Scope.Add("email");
                    options.Scope.Add("phone");
                    options.Scope.Add("ProductFly");

                    options.ClaimActions.MapAbpClaimTypes();

                    options.Events = new Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectEvents
                    {
                        // called if user clicks Cancel during login
                        OnAccessDenied = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/");
                            return System.Threading.Tasks.Task.CompletedTask;
                        }
                    };
                });

Кроме того, заметил, что у меня есть собственная страница входа, и я использую ее для сохранения мой принципал:

SignInAsyn c (CookieAuthenticationDefaults.AuthenticationScheme, новый ClaimsPrincipal (претендент Identity), authProperties);

Вот код установки IdentityServer:

private stati c void AddIdentityServer (IServiceCollection services) { var configuration = services.GetConfiguration (); var builderOptions = services.ExecutePreConfiguredActions ();

    var identityServerBuilder = services.AddIdentityServer(options =>
    {
        options.Events.RaiseErrorEvents = true;
        options.Events.RaiseInformationEvents = true;
        options.Events.RaiseFailureEvents = true;
        options.Events.RaiseSuccessEvents = true;
    });

    if (builderOptions.AddDeveloperSigningCredential)
    {
        identityServerBuilder = identityServerBuilder.AddDeveloperSigningCredential();
    }

    identityServerBuilder.AddInMemoryClients(configuration.GetSection("IdentityServer:Clients"));

    services.ExecutePreConfiguredActions(identityServerBuilder);

    if (!services.IsAdded<IPersistedGrantService>())
    {
        identityServerBuilder.AddInMemoryPersistedGrants();
    }

    if (!services.IsAdded<IClientStore>())
    {
        identityServerBuilder.AddInMemoryClients(configuration.GetSection("IdentityServer:Clients"));
    }

    if (!services.IsAdded<IResourceStore>())
    {
        identityServerBuilder.AddInMemoryApiResources(configuration.GetSection("IdentityServer:ApiResources"));
        identityServerBuilder.AddInMemoryIdentityResources(configuration.GetSection("IdentityServer:IdentityResources"));
    }
}

И для настройки используется следующая запись:

"GrantType": "client_credentials" "ClientId": "Product_App" "ClientName": "Product_App" "Описание": "Product_App" "ClientUri": null, "LogoUri": null, "Enabled": true, "ProtocolType": "oid c", "RequireClientSecret": true, " RequireConsent ": false," AllowRememberConsent ": true," AlwaysIncludeUserClaimsInIdToken ": true," RequirePkce ": false," AllowPlainTextPkce ": false," AllowAccessTokensViaBrowser ": false," FrontChannelLogoutUriS ": true, True" True, True "," True "," True ", true" true "," True ", true" true ", true:" : null, "BackChannelLogoutSessionRequired": true, "AllowOfflineAccess": true, "IdentityTokenLifetime": {"$ numberInt": "300"}, "AccessTokenLifetime": {"$ numberInt": "31536000"}, "AuthorizationCodeLifetime": { "$ numberInt": "300"}, "ConsentLifetime": null, "AbsoluteRefreshTokenLifetime": {"$ numberInt": "31536000"}, "SlidingRefreshTokenLifetime": {"$ numberInt": "1296000"}, "Обновить TokenUsage ": {" $ numberInt ":" 1 "}," UpdateAccessTokenClaimsOnRefre sh ": false," RefreshTokenExpiration ": {" $ numberInt ":" 1 "}," AccessTokenType ": {" $ numberInt ":" 0 "}," EnableLocalLogin ": true," IncludeJwtId ": false," AlwaysSendClientClaims ": false," ClientClaimsPrefix ":" client_ "," PairWiseSubjectSalt ": null," UserSsoLifetime ": null," UserCodeType Device ": nuifetime": nuife " : {"$ numberInt": "300"},

У кого-нибудь есть идея, чтобы решить эту проблему? Или хотя бы отладить его?

PS: Я ищу безуспешно несколько дней!

...