Skip to content
This repository was archived by the owner on Dec 13, 2018. It is now read-only.

Add SameSitePolicy to CookiePolicyMiddleware #1222

Merged
merged 1 commit into from
May 23, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ internal class ChunkingCookieManager
/// <summary>
/// The default maximum size of characters in a cookie to send back to the client.
/// </summary>
public const int DefaultChunkSize = 4070;
public const int DefaultChunkSize = 4050;

private const string ChunkKeySuffix = "C";
private const string ChunkCountPrefix = "chunks-";
Expand All @@ -42,7 +42,7 @@ public ChunkingCookieManager()
{
// Lowest common denominator. Safari has the lowest known limit (4093), and we leave little extra just in case.
// See http://browsercookielimits.x64.me/.
// Leave at least 20 in case CookiePolicy tries to add 'secure' and/or 'httponly'.
// Leave at least 40 in case CookiePolicy tries to add 'secure', 'samesite=strict' and/or 'httponly'.
ChunkSize = DefaultChunkSize;
ThrowForPartialCookies = true;
}
Expand Down Expand Up @@ -166,6 +166,7 @@ public void AppendResponseCookie(HttpContext context, string key, string value,
{
Domain = options.Domain,
Expires = options.Expires,
SameSite = (Net.Http.Headers.SameSiteMode)options.SameSite,
HttpOnly = options.HttpOnly,
Path = options.Path,
Secure = options.Secure,
Expand Down Expand Up @@ -284,6 +285,7 @@ public void DeleteCookie(HttpContext context, string key, CookieOptions options)
{
Path = options.Path,
Domain = options.Domain,
SameSite = options.SameSite,
Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
});

Expand All @@ -297,6 +299,7 @@ public void DeleteCookie(HttpContext context, string key, CookieOptions options)
{
Path = options.Path,
Domain = options.Domain,
SameSite = options.SameSite,
Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ private CookieOptions BuildCookieOptions()
var cookieOptions = new CookieOptions
{
Domain = Options.CookieDomain,
SameSite = Options.CookieSameSite,
HttpOnly = Options.CookieHttpOnly,
Path = Options.CookiePath ?? (OriginalPathBase.HasValue ? OriginalPathBase.ToString() : "/"),
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.Authentication.Cookies
{
Expand All @@ -23,6 +22,7 @@ public CookieAuthenticationOptions()
ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
ExpireTimeSpan = TimeSpan.FromDays(14);
SlidingExpiration = true;
CookieSameSite = SameSiteMode.Strict;
CookieHttpOnly = true;
CookieSecure = CookieSecurePolicy.SameAsRequest;
Events = new CookieAuthenticationEvents();
Expand Down Expand Up @@ -57,6 +57,12 @@ public string CookieName
/// </summary>
public string CookiePath { get; set; }

/// <summary>
/// Determines if the browser should allow the cookie to be attached to same-site or cross-site requests. The
/// default is Strict, which means the cookie is only allowed to be attached to same-site requests.
/// </summary>
public SameSiteMode CookieSameSite { get; set; }

/// <summary>
/// Determines if the browser should allow the cookie to be accessed by client-side javascript. The
/// default is true, which means the cookie will only be passed to http requests and is not made available
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -899,6 +899,7 @@ private void WriteNonceCookie(string nonce)
new CookieOptions
{
HttpOnly = true,
SameSite = Http.SameSiteMode.Lax,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

using?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is to differentiate between the one in M.A.Http and M.Net.Http.Headers. Both usings are already present and required.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Brings up a good point, Should I be using the one from M.A.Http or M.Net.Http.Headers when I have the choice? Is there a preference for any particular one?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stick with the aspnet one.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup that's the one I try to use as much as possible.

Secure = Request.IsHttps,
Expires = Clock.UtcNow.Add(Options.ProtocolValidator.NonceLifetime)
});
Expand Down Expand Up @@ -930,6 +931,7 @@ private string ReadNonceCookie(string nonce)
var cookieOptions = new CookieOptions
{
HttpOnly = true,
SameSite = Http.SameSiteMode.Lax,
Secure = Request.IsHttps
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ protected override async Task<AuthenticateResult> HandleRemoteAuthenticateAsync(
var cookieOptions = new CookieOptions
{
HttpOnly = true,
SameSite = SameSiteMode.Lax,
Secure = Request.IsHttps
};

Expand Down Expand Up @@ -160,6 +161,7 @@ protected override async Task HandleUnauthorizedAsync(ChallengeContext context)
var cookieOptions = new CookieOptions
{
HttpOnly = true,
SameSite = SameSiteMode.Lax,
Secure = Request.IsHttps,
Expires = Clock.UtcNow.Add(Options.RemoteAuthenticationTimeout),
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ protected virtual void GenerateCorrelationId(AuthenticationProperties properties
var cookieOptions = new CookieOptions
{
HttpOnly = true,
SameSite = SameSiteMode.Lax,
Secure = Request.IsHttps,
Expires = Clock.UtcNow.Add(Options.RemoteAuthenticationTimeout),
};
Expand Down Expand Up @@ -242,6 +243,7 @@ protected virtual bool ValidateCorrelationId(AuthenticationProperties properties
var cookieOptions = new CookieOptions
{
HttpOnly = true,
SameSite = SameSiteMode.Lax,
Secure = Request.IsHttps
};
Response.Cookies.Delete(cookieName, cookieOptions);
Expand Down
20 changes: 18 additions & 2 deletions src/Microsoft.AspNetCore.CookiePolicy/CookiePolicyMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public IResponseCookies Cookies

private bool PolicyRequiresCookieOptions()
{
return Policy.HttpOnly != HttpOnlyPolicy.None || Policy.Secure != CookieSecurePolicy.None;
return Policy.MinimumSameSitePolicy != SameSiteMode.None || Policy.HttpOnly != HttpOnlyPolicy.None || Policy.Secure != CookieSecurePolicy.None;
}

public void Append(string key, string value)
Expand Down Expand Up @@ -151,6 +151,22 @@ private void ApplyPolicy(CookieOptions options)
default:
throw new InvalidOperationException();
}
switch (Policy.MinimumSameSitePolicy)
{
case SameSiteMode.None:
break;
case SameSiteMode.Lax:
if (options.SameSite == SameSiteMode.None)
{
options.SameSite = SameSiteMode.Lax;
}
break;
case SameSiteMode.Strict:
options.SameSite = SameSiteMode.Strict;
break;
default:
throw new InvalidOperationException($"Unrecognized {nameof(SameSiteMode)} value {Policy.MinimumSameSitePolicy.ToString()}");
}
switch (Policy.HttpOnly)
{
case HttpOnlyPolicy.Always:
Expand All @@ -159,7 +175,7 @@ private void ApplyPolicy(CookieOptions options)
case HttpOnlyPolicy.None:
break;
default:
throw new InvalidOperationException();
throw new InvalidOperationException($"Unrecognized {nameof(HttpOnlyPolicy)} value {Policy.HttpOnly.ToString()}");
}
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/Microsoft.AspNetCore.CookiePolicy/CookiePolicyOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ namespace Microsoft.AspNetCore.Builder
/// </summary>
public class CookiePolicyOptions
{
/// <summary>
/// Affects the cookie's same site attribute.
/// </summary>
public SameSiteMode MinimumSameSitePolicy { get; set; } = SameSiteMode.Strict;

/// <summary>
/// Affects whether cookies must be HttpOnly.
/// </summary>
Expand Down
5 changes: 5 additions & 0 deletions test/Microsoft.AspNetCore.Authentication.Test/CookieTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ public async Task SignInCausesDefaultCookieToBeCreated()
Assert.StartsWith("TestCookie=", setCookie);
Assert.Contains("; path=/", setCookie);
Assert.Contains("; httponly", setCookie);
Assert.Contains("; samesite=", setCookie);
Assert.DoesNotContain("; expires=", setCookie);
Assert.DoesNotContain("; domain=", setCookie);
Assert.DoesNotContain("; secure", setCookie);
Expand Down Expand Up @@ -206,6 +207,7 @@ public async Task CookieOptionsAlterSetCookieHeader()
o.CookiePath = "/foo";
o.CookieDomain = "another.com";
o.CookieSecure = CookieSecurePolicy.Always;
o.CookieSameSite = SameSiteMode.None;
o.CookieHttpOnly = true;
}, SignInAsAlice, baseAddress: new Uri("http://example.com/base"));

Expand All @@ -217,12 +219,14 @@ public async Task CookieOptionsAlterSetCookieHeader()
Assert.Contains(" path=/foo", setCookie1);
Assert.Contains(" domain=another.com", setCookie1);
Assert.Contains(" secure", setCookie1);
Assert.DoesNotContain(" samesite", setCookie1);
Assert.Contains(" httponly", setCookie1);

var server2 = CreateServer(o =>
{
o.CookieName = "SecondCookie";
o.CookieSecure = CookieSecurePolicy.None;
o.CookieSameSite = SameSiteMode.Strict;
o.CookieHttpOnly = false;
}, SignInAsAlice, baseAddress: new Uri("http://example.com/base"));

Expand All @@ -232,6 +236,7 @@ public async Task CookieOptionsAlterSetCookieHeader()

Assert.Contains("SecondCookie=", setCookie2);
Assert.Contains(" path=/base", setCookie2);
Assert.Contains(" samesite=strict", setCookie2);
Assert.DoesNotContain(" domain=", setCookie2);
Assert.DoesNotContain(" secure", setCookie2);
Assert.DoesNotContain(" httponly", setCookie2);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public void AppendLargeCookie_Appended()
new ChunkingCookieManager() { ChunkSize = null }.AppendResponseCookie(context, "TestCookie", testString, new CookieOptions());
var values = context.Response.Headers["Set-Cookie"];
Assert.Equal(1, values.Count);
Assert.Equal("TestCookie=" + testString + "; path=/", values[0]);
Assert.Equal("TestCookie=" + testString + "; path=/; samesite=lax", values[0]);
}

[Fact]
Expand All @@ -27,20 +27,20 @@ public void AppendLargeCookieWithLimit_Chunked()
HttpContext context = new DefaultHttpContext();

string testString = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
new ChunkingCookieManager() { ChunkSize = 30 }.AppendResponseCookie(context, "TestCookie", testString, new CookieOptions());
new ChunkingCookieManager() { ChunkSize = 44 }.AppendResponseCookie(context, "TestCookie", testString, new CookieOptions());
var values = context.Response.Headers["Set-Cookie"];
Assert.Equal(9, values.Count);
Assert.Equal<string[]>(new[]
{
"TestCookie=chunks-8; path=/",
"TestCookieC1=abcdefgh; path=/",
"TestCookieC2=ijklmnop; path=/",
"TestCookieC3=qrstuvwx; path=/",
"TestCookieC4=yz012345; path=/",
"TestCookieC5=6789ABCD; path=/",
"TestCookieC6=EFGHIJKL; path=/",
"TestCookieC7=MNOPQRST; path=/",
"TestCookieC8=UVWXYZ; path=/",
"TestCookie=chunks-8; path=/; samesite=lax",
"TestCookieC1=abcdefgh; path=/; samesite=lax",
"TestCookieC2=ijklmnop; path=/; samesite=lax",
"TestCookieC3=qrstuvwx; path=/; samesite=lax",
"TestCookieC4=yz012345; path=/; samesite=lax",
"TestCookieC5=6789ABCD; path=/; samesite=lax",
"TestCookieC6=EFGHIJKL; path=/; samesite=lax",
"TestCookieC7=MNOPQRST; path=/; samesite=lax",
"TestCookieC8=UVWXYZ; path=/; samesite=lax",
}, values);
}

Expand Down Expand Up @@ -116,14 +116,14 @@ public void DeleteChunkedCookieWithOptions_AllDeleted()
Assert.Equal(8, cookies.Count);
Assert.Equal(new[]
{
"TestCookie=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/",
"TestCookieC1=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/",
"TestCookieC2=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/",
"TestCookieC3=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/",
"TestCookieC4=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/",
"TestCookieC5=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/",
"TestCookieC6=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/",
"TestCookieC7=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/",
"TestCookie=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; samesite=lax",
"TestCookieC1=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; samesite=lax",
"TestCookieC2=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; samesite=lax",
"TestCookieC3=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; samesite=lax",
"TestCookieC4=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; samesite=lax",
"TestCookieC5=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; samesite=lax",
"TestCookieC6=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; samesite=lax",
"TestCookieC7=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=foo.com; path=/; samesite=lax",
}, cookies);
}
}
Expand Down
Loading