Prologue

In the previous post, we introduced a practical way to enable CORS in ASP.NET Core, in which configuration for cookies is mentioned. If you haven’t see that one, I recommend you spend some time now.

Not only requests will be affected by CORS policy, Cookies will, too. Or, you can take that Cookies are part of the requests. So in this post, I will breakdown more detail on how to properly handle Cookies in ASP.NET Core Web API.


1. Configure CORS

Before we use Cookies, we have to configure CORS policy for it, since it is different from regular requests. For details, please refer to the post I mentioned above.

The only additional configuration that Cookies require is AllowCredentials().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddCors(options => {
options.AddPolicy(
name: /* policy name */,
policy => {
policy.AllowCredentials(); // for cookies
});
});
}
}

2. “Make” Cookies

All Cookies operations should be done in Controllers, since it uses Request and Response, or you can pass it to somewhere else.

2.1 Add Cookies

You can declare a utility function to add Cookies into response. It will add a Set-Cookie header in response, resulting in a creation or update of the given Cookie on client side.

Please ignore bad syntax highlight for value. 🥴

1
2
3
4
5
6
7
public void SetCookie(string key, string value, double expires)
{
Response.Cookies.Append(key, value, new CookieOptions {
HttpOnly = true,
Expires = DateTime.Now.AddDays(expires)
});
}

You may notice the CookieOptions parameter. Well, this is somehow necessary, and important. Usually, the expire time is assigned here.

For sensitive information, which we do not want to be easily modified by client side, we can set its HttpOnly to true, so that this Cookie entry can only be modified by the Server with response. In this way, client side could not modify (update, delete or else) it. Although the DevTools of the browser can still do anything it likes. 🤪

Once you set HttpOnly to true, you can not modify it on client side. Use it only when necessary.

2.2 Delete Cookies

Similar to add Cookies, you can set the expire date to a previous time in the history to make it invalid. Set HttpOnly correspondingly.

1
2
3
4
5
6
7
public void DeleteCookie(string key)
{
Response.Cookies.Append(key, "", new CookieOptions {
HttpOnly = true,
Expires = DateTime.Now.AddDays(-1)
});
}

Or, you can simply call Delete() on Cookies. In this case, we don’t need HttpOnly, and it can apply to both types of Cookies.

1
2
3
4
public void DeleteCookie(string key)
{
Response.Cookies.Delete(key);
}

2.3 Get Cookies

Oh, wait a minute! We haven’t say how to get Cookies in requests! 😳 But quite simple, it is.

1
var cookie = Request.Cookies[key];

If Cookie with key doesn’t exist, null is returned.


Epilogue

Well, this is it. Yummy Cookies ~ 😉