OpenIddictHandler не обрабатывает HTTP-запрос после первого раза - PullRequest
0 голосов
/ 20 марта 2019

У меня возникла проблема с сервером авторизации OpenIdDict. Я настроил его для потока паролей, также я использую пользовательские объекты для авторизации и токены. Когда я в первый раз пытаюсь войти на конечную точку токена, после запуска приложения все работает нормально. В журнале отладки я вижу это сообщение.

[2019.03.20 09:35:58] [40m[32minfo[39m[22m[49m: WebHost[1]      Request starting HTTP/1.1 POST http://localhost:32791/api/v1/oauth/token application/x-www-form-urlencoded 152
Loaded '/root/.nuget/packages/aspnet.security.openidconnect.extensions/2.0.0-rc1-final/lib/netstandard2.0/AspNet.Security.OpenIdConnect.Extensions.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
[2019.03.20 09:35:59] [40m[32minfo[39m[22m[49m: OpenIddictHandler      The token request was successfully extracted from the HTTP request: {
"username": "oleg@gmail.com",
"password": "[removed for security reasons]",
"BusinessType": "HairSalon",
"TimeZone": "PacificPagoPago",
"Currency": "AED",
"Country": "ABW",
"grant_type": "password",
"SignUp": "false"
}.
[2019.03.20 09:35:59] [40m[37mdbug[39m[22m[49m: OpenIddictProvider      The token request validation process was partially skipped because the 'client_id' parameter was missing or empty.
[2019.03.20 09:35:59] [40m[32minfo[39m[22m[49m: OpenIddictHandler      The token request was successfully validated.
[2019.03.20 09:35:59] [40m[37mdbug[39m[22m[49m: OpenIddictHandler      The default token request handling was skipped from user code.
[2019.03.20 09:35:59] [40m[32minfo[39m[22m[49m: ControllerActionInvoker[1]      Executing action method MyProject.Controllers.OAuthTokenController.Post (MyProject) with arguments (MyProject.Models.UserModel) - ModelState is Valid
...

Но все другие будущие запросы (до перезапуска проекта) выдают InvalidOperationException: InvalidOperationException: от этой конечной точки невозможно вернуть ответ авторизации или токена. После того, как я нахожу описание этой ошибки, я снова вижу журналы вывода отладки и вижу, что во всех запросах, кроме первого, нет сообщений от OpenIddictHandler. Отладочный вывод:

[2019.03.20 09:36:24] [40m[32minfo[39m[22m[49m: WebHost[1]      Request starting HTTP/1.1 POST http://localhost:32791/api/v1/oauth/token application/x-www-form-urlencoded 151
[2019.03.20 09:36:24] [40m[32minfo[39m[22m[49m: ObjectResultExecutor[1]      Executing ObjectResult, writing value Microsoft.AspNetCore.Mvc.ControllerContext.
[2019.03.20 09:36:24] [40m[32minfo[39m[22m[49m: ControllerActionInvoker[1]      Executing action method MyProject.Controllers.OAuthTokenController.Post (MyProject) with arguments (MyProject.Models.UserModel) - ModelState is Valid
[2019.03.20 09:36:27] [40m[32minfo[39m[22m[49m: Infrastructure[10403]      Entity Framework Core 2.2.0-rtm-35687 initialized 'MyDbContext' using provider 'Pomelo.EntityFrameworkCore.MySql' with options: None
[2019.03.20 09:36:27] [40m[32minfo[39m[22m[49m: ControllerActionInvoker[2]      Executed action MyProject.Controllers.OAuthTokenController.Post (MyProject) in 28329.7586ms
[2019.03.20 09:36:27] [40m[32minfo[39m[22m[49m: WebHost[2]      Request finished in 28835.2212ms 400 application/json; charset=utf-8
[2019.03.20 09:36:27] [40m[32minfo[39m[22m[49m: Command[20101]      Executed DbCommand (13ms) [Parameters=[@__normalizedUserName_0='?' (Size = 256)], CommandType='Text', CommandTimeout='30']
SELECT `u`.`Id`, `u`.`ConfirmationToken`, `u`.`CreatedAt`, `u`.`Email`, `u`.`FirstName`, `u`.`LastName`, `u`.`Login`, `u`.`Mobile`, `u`.`NormalizedLogin`, `u`.`Password`, `u`.`RoleId`, `u`.`SecurityStamp`, `u`.`TokenSecurityStamp`, `u`.`UpdatedAt`
FROM `Users` AS `u`
WHERE `u`.`NormalizedLogin` = @__normalizedUserName_0
LIMIT 1
[2019.03.20 09:36:27] [40m[32minfo[39m[22m[49m: Command[20101]      Executed DbCommand (21ms) [Parameters=[@__normalizedUserName_0='?' (Size = 256)], CommandType='Text', CommandTimeout='30']
SELECT `u`.`Id`, `u`.`ConfirmationToken`, `u`.`CreatedAt`, `u`.`Email`, `u`.`FirstName`, `u`.`LastName`, `u`.`Login`, `u`.`Mobile`, `u`.`NormalizedLogin`, `u`.`Password`, `u`.`RoleId`, `u`.`SecurityStamp`, `u`.`TokenSecurityStamp`, `u`.`UpdatedAt`
FROM `Users` AS `u`
WHERE `u`.`NormalizedLogin` = @__normalizedUserName_0
LIMIT 1
[2019.03.20 09:36:27] [40m[32minfo[39m[22m[49m: Command[20101]      Executed DbCommand (70ms) [Parameters=[@__user_RoleId_0='?' (DbType = Guid)], CommandType='Text', CommandTimeout='30']
SELECT `r`.`Name`
FROM `Roles` AS `r`
WHERE `r`.`Id` = @__user_RoleId_0
[2019.03.20 09:36:32] [40m[32minfo[39m[22m[49m: SignInResult[1]      Executing SignInResult with authentication scheme (ASOS) and the following principal: System.Security.Claims.ClaimsPrincipal.
[2019.03.20 09:36:32] [40m[32minfo[39m[22m[49m: ControllerActionInvoker[2]      Executed action MyProject.Controllers.OAuthTokenController.Post (MyProject) in 8564.2121ms
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.9/System.Diagnostics.StackTrace.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Loaded '/usr/share/dotnet/shared/Microsoft.NETCore.App/2.0.9/System.Reflection.Metadata.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
[2019.03.20 09:36:32] [41m[30mfail[39m[22m[49m: DeveloperExceptionPageMiddleware      An unhandled exception has occurred while executing the request
System.InvalidOperationException: An authorization or token response cannot be returned from this endpoint.
...

Как видите, сообщений об OpenIddictHandler нет. Я понятия не имею, почему это происходит, и буду благодарен за помощь.

Вот моя конфигурация OpenIdDict.

services.Configure<IdentityOptions>(options =>
{
    options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
    options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
    options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
});

var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(settings.TokenSigningKey));
services.AddOpenIddict<OpenIddictApplication, Authorization, OpenIddictScope, Token>(options =>
{
    options.AddAuthorizationStore<OpenIddictAuthorizationStore>();
    options.AddTokenStore<OpenIddictTokenStore>();
    options.AddApplicationStore<OpenIddictApplicationStore<MyDbContext>>();
    options.AddScopeStore<OpenIddictScopeStore<MyDbContext>>();
    options.AddMvcBinders();
    options.EnableTokenEndpoint("/api/v1/oauth/token");
    options.AllowPasswordFlow();
    options.AllowRefreshTokenFlow();
    options.UseJsonWebTokens();
    options.AddSigningKey(signingKey);
    options.SetAccessTokenLifetime(settings.AccessTokenLifetime);
    options.SetRefreshTokenLifetime(settings.RefreshTokenLifetime);
    if (!settings.EnableTokenAuthHttpsRequirement)
    {
        options.DisableHttpsRequirement();
    }
});

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = settings.JwtAuthority;
        options.Audience = settings.JwtAudience;
        options.MetadataAddress = settings.JwtMetadataAddress;
        options.RequireHttpsMetadata = settings.EnableTokenAuthHttpsRequirement;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = signingKey,
            ValidIssuers = settings.JwtIssuers,
            NameClaimType = OpenIdConnectConstants.Claims.Subject,
            RoleClaimType = OpenIdConnectConstants.Claims.Role
        };
        options.IncludeErrorDetails = hostingEnvironment.IsDevelopment();
    });

services.AddScoped<IOpenIddictAuthorizationStore<Authorization>, OpenIddictAuthorizationStore>();
services.AddScoped<IOpenIddictTokenStore<Token>, OpenIddictTokenStore>();

Большое спасибо!

1 Ответ

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

Я нашел ошибку, мой плохой.Я регистрирую app.UseMvc () перед app.UseAuthentication ();в Startup.cs и т. д. промежуточное программное обеспечение OpenIdDict вызывает после действий Mvc.

...