Skip to content

Instantly share code, notes, and snippets.

@mkropat
Created December 18, 2018 21:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkropat/e98bf09be76f7bea9cca91aa21b725de to your computer and use it in GitHub Desktop.
Save mkropat/e98bf09be76f7bea9cca91aa21b725de to your computer and use it in GitHub Desktop.
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
public enum SameSitePolicy
{
Strict,
Lax,
}
public class SameSiteCookieMiddleware : OwinMiddleware
{
private const string SetCookieHeader = "Set-Cookie";
private readonly PathString loginPath;
private readonly SameSitePolicy policy;
public SameSiteCookieMiddleware(OwinMiddleware next, PathString loginPath, SameSitePolicy policy) : base(next)
{
this.loginPath = loginPath;
this.policy = policy;
}
public override async Task Invoke(IOwinContext context)
{
if (context.Request.Path.StartsWithSegments(loginPath))
{
context.Response.OnSendingHeaders(
x => SetPolicyOnSetCookieHeader(context.Response),
null);
}
await Next.Invoke(context);
}
private void SetPolicyOnSetCookieHeader(IOwinResponse response)
{
if (!response.Headers.ContainsKey(SetCookieHeader))
{
return;
}
var cookieValues = response.Headers.GetValues(SetCookieHeader);
var updatedValues = cookieValues.Select(v => v + $"; SameSite={policy}").ToArray();
response.Headers.SetValues(SetCookieHeader, updatedValues);
}
}
public static class SameSiteCookieMiddlewareExtensions
{
public static IAppBuilder UseSameSiteCookies(this IAppBuilder builder, PathString loginPath, SameSitePolicy policy = SameSitePolicy.Strict)
{
builder.Use(typeof(SameSiteCookieMiddleware), loginPath, policy);
return builder;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment