使用AntiforgeryToken从ASPNET.CORE获得400状态

时间:2018-06-27 13:09:13

标签: c# asp.net-core

我有一个带有.net核心Api的angular 4应用程序。我想提出一些终结点防伪验证。这样,我设法在浏览器的cookie中获得了令牌。

这是startup.cs-配置:

if (env.IsDevelopment())
{
}

app.UseDeveloperExceptionPage();

app.UseCors("AllowAll");
app.Use(next => context =>
{
    string method = context.Request.Method;
    if (method == "GET")
    {
        var tokens = antiforgery.GetAndStoreTokens(context);
        context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
             new CookieOptions()
             {
                 HttpOnly = false,

             });
    }
    return next(context);

});

这是来自ConfigureServices:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme =
                               JwtBearerDefaults.AuthenticationScheme;

    options.DefaultChallengeScheme =
                               JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
    o.Authority = Configuration["IdentityServer"];
    o.Audience = "MyApi";
    o.RequireHttpsMetadata = false;

});

services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
    builder.AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader()
           .AllowCredentials();
}));

services.AddAntiforgery(options =>
{
    options.HeaderName = "X-XSRF-TOKEN";
    options.RequireSsl = false;
    options.SuppressXFrameOptionsHeader = false;
});

这在控制器中:

[Authorize]
[ValidateAntiForgeryToken]
[HttpPost, Route("irrelevant")]
public IActionResult CalledByTheFront([FromBody] irrelevant)
{
    return Ok("irrelevant");
}

我在浏览器中找到的cookie enter image description here

请求:enter image description here

我在做什么错? 附言另外,您知道为什么为什么浏览器中的Cookie仅在API重新启动时才更新,尽管每个GET请求的标头中都有Cookie吗?

0 个答案:

没有答案