Skip to content

Instantly share code, notes, and snippets.

@jacobmohl
Last active April 4, 2023 00:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacobmohl/cf90c5d38185eed3782cfe0b393f03c7 to your computer and use it in GitHub Desktop.
Save jacobmohl/cf90c5d38185eed3782cfe0b393f03c7 to your computer and use it in GitHub Desktop.
Example of creating cookies inside a Azure Function
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
namespace FunctionCookieExample
{
public static class MyFunction
{
[FunctionName("MyFunction")]
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req)
{
// Read a cookie
var cookieValue = req.Cookies["MyCookie"];
// Set a cooke
//// Configure the cookie
CookieOptions option = new CookieOptions();
option.Expires = DateTime.Now.AddYears(1);
option.Domain = ".mydomain.tld";
//// Make the cookie available for the browser
option.HttpOnly = true;
//// A little non logical way to actually get the HttpResponse (from the HttpRequest and its HttpContext)
req.HttpContext.Response.Cookies.Append("MyCookie", "MyValue", option);
return new OkObjectResult("Cookie set");
}
}
}
@alena-grischenko
Copy link

Thanks a lot!

@SikoSoft
Copy link

Does it work to set any arbitrary custom domain name as you've done here with .mydomain.tld? Is any configuration required in the Azure side of things to create cookies under custom domains?

@jacobmohl
Copy link
Author

@SikoSoft it needs at least to be the (custom) tld domain the function is working in. Browsers don’t allow you to set cookies from other domains.

@MDBrittingham
Copy link

Yes, thank you. ChatGPT fell apart on this one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment