简体   繁体   中英

Unable to validate Antiforgery token when cookie is set to httponly

When i set the value of httponly=true. AutoValidateAntiforgeryTokenAttribute doesnot validate the request and return 400 bad request

AntiforgeryTokenSet tokens = antiforgery.GetAndStoreTokens(context);
   context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
    new CookieOptions() { HttpOnly = true});

After doing this cookie become secure as shown below

set-cookie: XSRF-TOKEN={{Cookie Value}}; path=/; samesite=lax; httponly

But AutoValidateAntiforgeryTokenAttribute returns 400 bad request

when changed the Value HttpOnly = true to HttpOnly = false

It works perfectly fine. Is there is way to set antiforgerytoken cookie to httponly in asp core and angular 7. If it will not work can some body please guide me through about the reason behind it.

No, it's not possible for this particular cookie to be set to http-only. To understand why , have a look at the following section from the ASP.NET Core docs :

AngularJS uses a convention to address CSRF. If the server sends a cookie with the name XSRF-TOKEN , the AngularJS $http service adds the cookie value to a header when it sends a request to the server.

This talks about AngularJS and $http , but the same mechanism is used for Angular and its HttpClient service (see the Angular docs ).

To be able to add the cookie value to a header, Angular must be able to read the value out of the cookie. When you set the cookie to HttpOnly , Angular is unable to read the value from the cookie (it's as if it doesn't even exist). Thus the value is not sent and the server rejects the request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM