Why AntiForgeryToken validation keeps failing?

前端 未结 3 1970
日久生厌
日久生厌 2021-01-22 23:34

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

相关标签:
3条回答
  • 2021-01-23 00:14

    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.

    0 讨论(0)
  • 2021-01-23 00:17

    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

    0 讨论(0)
  • 2021-01-23 00:32

    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.

    0 讨论(0)
提交回复
热议问题