HttpOnly Cookies in ASP.net Core

HttpOnly is a flag that can be used when setting a cookie to block access to the cookie from client side scripts. Javascript for example cannot read a cookie that has HttpOnly set. This helps mitigate a large part of XSS attacks as many of these attempt to read cookies and send them back to the attacker, possibly leaking sensitive information or worst case scenario, allowing the attacker to impersonate the user with login cookies.

If you are interested in reading more on the background of HttpOnly cookies, OWASP has a great article here explaining them in more detail : https://www.owasp.org/index.php/HttpOnly

Now, onto how these can used in .net core.

Defaults Are Gone

An important thing to note in .net core compared to the .net framework, is that while previously you were able to set global defaults, you can no longer do this. For example in .net framework you were able to add the following to your web.config :

This would make sure that any cookies set by your application were HttpOnly. Obviously web.config is more or less out the window with .net core (Although if you are hosting on IIS you can still use it), and Microsoft hasn’t added in a global default able to be set yet. This may change in the future however because it was definitely a handy setting.

Setting A Cookie Manually

When setting a cookie manually (e.g. against an HTTPContext), there is an easy CookieOptions object that you can use to set HttpOnly to true. It ends up looking a bit like this :

When Using Cookie Authentication

Microsoft have a middleware that uses cookies for Authentication. If you were to use it in your app, you add it in the Configure method of your startup.cs.

If you are using CookieAuthentication in this way, HttpOnly cookies will be used by default. (You can check the source code here on Github). If you actually need this functionality off (Dangerous, but it’s a possibility), then you can override the functionality like so :

When Using XYZ Middleware

Because there is no global option for HttpOnly cookies, when using a third party middleware you are at their mercy as to how they set their cookies and whether they are HttpOnly or not. In some cases they may not be HttpOnly when you want them to be, and even vice versa when you actually need the cookie to be accessible. If you are building your own middleware that you intend to share as a library, the best option is leaving the default as HttpOnly set to true, and allowing the user to override it if they really feel the need.

Leave a Reply

Your email address will not be published. Required fields are marked *