Why AntiForgeryToken validation keeps failing?

2019-01-28 22:36发布

问题:

I am developing a web API app running using asp.net core2 and Angular. The detailed development environment config is here. I am trying to configure AntiForgeryToken validation but it keeps failing. I followed the config. here, but I had to modify it as my angular app and asp.net servers are running on two different ports because the front end startup doesn't generate the token. I kick start the backend by calling an API path (/api/Account/ContactInitialization) at the app component ngOnInit which allowed me to generate the token. The config is shown below,

IServiceCollection Service:

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

and at IApplicationBuilder Configure:

app.Use(next => context =>
                {
                    string path = context.Request.Path.Value;
                    if (

                        string.Equals(path, "/", StringComparison.OrdinalIgnoreCase) ||
                        string.Equals(path, "/api/Account/ContactInitialization", StringComparison.OrdinalIgnoreCase) ||
                        string.Equals(path, "/index.html", StringComparison.OrdinalIgnoreCase))
                    {
                        // We can send the request token as a JavaScript-readable cookie, 
                        // and Angular will use it by default.
                         var tokens = antiforgery.GetAndStoreTokens(context);
                        context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                            new CookieOptions() { HttpOnly = false });
                    }

                    return next(context);
                });

asp.net. generates two set of keys,

I decorated my method with [ValidateAntiForgeryToken] and I included XSRF-TOKEN cookie content in my header request. yet I keep receiving a 400 (Bad Request) response after calling the API! what am I missing here?

Controller Method,

    [Authorize]
    [ValidateAntiForgeryToken]
    [HttpPost]
    public IEnumerable<string> AutherizeCookie()
    {
        return new string[] { "Hello", "Auth Cookie" };
    }

my detailed header request looks like below,

回答1:

I'm assuming you probably followed the documentation, but glossed over the pertinent bits. What you've done so far works only for Angular, because Angular's $http will actually add the X-XSRF-TOKEN header based on the XSRF-TOKEN cookie. (Note, however, that even then, you've set your header as X-CSRF-TOKEN, which won't actually work here. It needs to be X-XSRF-TOKEN).

However, if you're not using Angular, you're responsible for setting the header yourself in your AJAX requests, which you likely are neglecting to do. In this case, you don't actually need to change any of the antiforgery token config (header names, setting cookies, etc.). You simply need to provide the header as RequestVerificationToken. For example, with jQuery:

$.ajax({
    ...
    headers:
    {
        "RequestVerificationToken": '@GetAntiXsrfRequestToken()'
    },
    ...
});

That will work for JavaScript in view. If you need to do this in external JS, then you would need to set the cookie, so that you can get at the value from the cookie instead. Other than that, the same methodology applies.

If you simply want to change the header name, you can do so; you just need to change the RequestVerificationHeader portion here to the same value.



回答2:

You need to issue the XHR Request withCredentials=true that will make the browser sets the cookie, other wise you will get the 400 bad request because cookie is absent and the X-XSRF-TOKEN is either not set or set to empty string



回答3:

thanks, @Chris_Pratt for pointing out the header issue that I had. However, in order to make it clear I had other issues which will address below.

I had my CORS misconfigured, my working code is the following,

services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder
                        .WithOrigins("https://www.artngcore.com:4200") //Note:  The URL must be specified without a trailing slash (/).
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());
            });

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

and the middleware configuration is,

app.Use(next => context =>
               {
                   string path = context.Request.Path.Value;
                   var tokens = antiforgery.GetAndStoreTokens(context);
                   context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                        new CookieOptions() { HttpOnly = false, 
Secure = true // set false if not using SSL });
                   return next(context);
               });

and in the controller,

[Route("/api/[controller]/[action]")]
[EnableCors("CorsPolicy")]
public class AccountController : ArtCoreSecuredController ....

what does the trick here is that the token has to refresh after authentication. calling an API just after authentication (login) will do it. don't forget to add the following header to your request,

 const headers = new HttpHeaders({
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.cookieService.get('ArtCoreToken')}`,
            'X-XSRF-TOKEN': `${this.cookieService.get('XSRF-TOKEN')}`
        });

i.e,

    [HttpGet]
    [AllowAnonymous]
    public async Task<IActionResult> RefreshToken()
    {
        await Task.Delay(1);

        return StatusCode(200);

    } 

this is what worked for me. hope it helps.