Why AntiForgeryToken validation keeps failing?
Asked Answered
B

3

3

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,

enter image description here

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,

Header Request

Basically answered 31/12, 2017 at 0:19 Comment(2)
LGTM. Tried removing the if conditions from the middleware?Michalmichalak
I am not having problems with generating the token if u mean, otherwise please explain why to remove the conditionBasically
L
6

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.

Logarithmic answered 2/1, 2018 at 16:52 Comment(5)
I am using Angular and it attaches the cookie by default as you said. I changed the provided header for the Token to X-XSRF-TOKEN yet I still get the same response,Basically
the code looks like below services.AddAntiforgery(options => { options.HeaderName = "X-XSRF-TOKEN"; }); and. var tokens = antiforgery.GetAndStoreTokens(context); context.Response.Cookies.Append("X-XSRF-TOKEN", tokens.RequestToken,..Basically
I don't make this post too long, but I have posted my startup config here , in my code, I changed my header to be X-XSRF-TOKENBasically
The cookie name is supposed to just be XSRF-TOKENLogarithmic
changed to var tokens = antiforgery.GetAndStoreTokens(context); context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken and I kept the header as X-XSRF-TOKEN, did not work, I wish I am receiving errors, nothing but a 400 bad request.Basically
N
1

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

Nighthawk answered 25/1, 2018 at 20:37 Comment(0)
B
0

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.

Basically answered 18/1, 2018 at 20:53 Comment(3)
I didn't understand why is RefreshToken call should be made? Is it because of CORS? For me, it is pretty much the same case except I don't have CORs enabled and I need to logout and login again in my webapp to make calls work.Piece
Please refer to this issue here, by design the key has to be refreshed after auth.Basically
Hm I'm having few doubts on this. Does not using ValidateAntiForegeryToken mean that your controller is not actually validating the csrf token, but only checking the CORS policy? Edit: actually just tested this; I removed the actual csrf token from my front end (the request sends a dummy csrf token that wasn't provided by the backend) and it's allowing the requestSheepshead

© 2022 - 2024 — McMap. All rights reserved.