How to implement X-XSRF-TOKEN with angular2 app and net core app?

前端 未结 2 916
灰色年华
灰色年华 2021-02-10 10:26

I have my net core app and antiforgery middlweare set up in Startup.cs:

        services.AddAntiforgery(options => options.HeaderName = \"X-XSRF-TOKEN\");
         


        
2条回答
  •  佛祖请我去吃肉
    2021-02-10 10:45

    Thanks to the CookieXSRFStrategy provided by Angular, Angular does that part for you.

    In the case of Angular, you will be using their $http service for sending AJAX requests. This service will automatically include a header with the name X-XSRF-TOKEN if it can find the token value as a cookie with the name XSRF-TOKEN.

    At the .net end you just have to create some middleware that will get the request token, and store its value as the XSRF-TOKEN cookie (HttpOnly = false).

    Validation Process:-

    1) The application will send back to the browser a cookie XSRF-TOKEN with the request token and another cookie .AspNetCore.Antiforgery.* with the cookie token.

    2) Whenever Angular sends an Ajax request, the request will include a header X-XSRF-TOKEN with the request token and the cookie .AspNetCore.Antiforgery.* with the cookie token.

    3) The Antiforgery validation will make sure that both tokens are valid and share the same secret, etc.

    Since the default header name for the request token is RequestVerificationToken, we need to change it and make sure Antiforgery searches for the request token in a header with name X-XSRF-TOKEN. Let’s just manually add Antiforgery and setup the options in the ConfigureServices method:

    services.AddAntiforgery(opts => opts.HeaderName = "X-XSRF-Token");
    

    Now we need to make sure we generate the tokens and include the request token in a cookie with name XSRF-TOKEN so Angular $http service can read it and include it as the header.

    This cannot be an http only cookie, since Angular code needs to read the cookie value so it can be included as a header in subsequent requests!

提交回复
热议问题