Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

c# - Why AntiForgeryToken validation keeps failing?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...