Получение 400 ошибок на ajax-запросах.Маркер защиты от подделки для пользователя на основе утверждений, отличного от текущего пользователя - PullRequest
0 голосов
/ 29 ноября 2018

Я использую ASP.NET CORE 2.1

Конфигурация:

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentity<User, Role>(options =>
    {
    })
    .AddEntityFrameworkStores<WebSiteDataContext>()
    .AddClaimsPrincipalFactory<CustomClaimsPrincipalFactory>()
    .AddDefaultTokenProviders();

   services.AddIdentityServer()
        .AddDeveloperSigningCredential() 
        .AddInMemoryPersistedGrants()
        .AddInMemoryIdentityResources(
            new List<IdentityResource>
            {
                   new IdentityResources.OpenId(),
                   new IdentityResources.Profile()
            })
        .AddInMemoryApiResources(new List<ApiResource> { new ApiResource(systemApiName) })
        .AddInMemoryClients(
            new List<Client>
            {
                   new Client
                   {
                       ClientId = clientId,                                           
                       ClientName = clientName,                                     
                       AllowedGrantTypes = GrantTypes.HybridAndClientCredentials
                           .Concat(GrantTypes.ResourceOwnerPassword).ToList(), 
                       ClientSecrets = { new Secret(secretKey.Sha256()) },                       
                       AllowedScopes =
                       {
                           IdentityServerConstants.StandardScopes.OpenId,
                           IdentityServerConstants.StandardScopes.Profile,
                           systemApiName
                       },
                       AllowAccessTokensViaBrowser = true,
                       AlwaysSendClientClaims = true,
                       AlwaysIncludeUserClaimsInIdToken = true,
                       AccessTokenLifetime = 3600 * 24          
                   }
            }
        )
        .AddAspNetIdentity<User>()            
        .AddProfileService<ProfileService>();

    services.AddAuthentication(options => options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme)
        .AddIdentityServerAuthentication(options =>
        {
            options.Authority = authorityEndPoint;
            options.ApiName = systemApiName;
            options.RequireHttpsMetadata = false;
            options.NameClaimType = "name";
            options.RoleClaimType = "role";
        });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAntiforgery antiforgery)
{
    app.UseIdentityServer();
    app.Use(next => ctx =>
    {
        var tokens = antiforgery.GetAndStoreTokens(ctx);
        ctx.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
            new CookieOptions() { HttpOnly = false });
        return next(ctx);
    });
}

И использую проверку токенов Antiforgery так же, как в https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-2.1

Но когда я отправляю заголовок 'Авторизация 'с токеном в запросе ajax, чем у меня ошибка

AntiforgeryValidationException: предоставленный токен защиты от подделки был предназначен для пользователя, основанного на утверждениях, чем текущий пользователь

Если я удаляю заголовок' Авторизация'или атрибут [ValidateAntiForgeryToken], чем нет ошибок.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...