/// <inheritdoc /> public void Append(string key, string value) { var setCookieHeaderValue = new SetCookieHeaderValue( Uri.EscapeDataString(key), Uri.EscapeDataString(value)) { Path = "/" }; string cookieValue; if (_builderPool == null) { cookieValue = setCookieHeaderValue.ToString(); } else { var stringBuilder = _builderPool.Get(); try { setCookieHeaderValue.AppendToStringBuilder(stringBuilder); cookieValue = stringBuilder.ToString(); } finally { _builderPool.Return(stringBuilder); } } Headers[HeaderNames.SetCookie] = StringValues.Concat(Headers[HeaderNames.SetCookie], cookieValue); }
/// <summary> /// Add a new cookie and value /// </summary> /// <param name="key"></param> /// <param name="value"></param> public void Append(string key, string value) { var setCookieHeaderValue = new SetCookieHeaderValue( UrlEncoder.Default.Encode(key), UrlEncoder.Default.Encode(value)) { Path = "/" }; Headers[HeaderNames.SetCookie] = StringValues.Concat(Headers[HeaderNames.SetCookie], setCookieHeaderValue.ToString()); }
public void SetCookieHeaderValue_TryParse_ExtensionOrderDoesntMatter() { string cookieHeaderValue1 = "cookiename=value; extensionname1=value; extensionname2=value;"; string cookieHeaderValue2 = "cookiename=value; extensionname2=value; extensionname1=value;"; SetCookieHeaderValue setCookieHeaderValue1; SetCookieHeaderValue setCookieHeaderValue2; SetCookieHeaderValue.TryParse(cookieHeaderValue1, out setCookieHeaderValue1); SetCookieHeaderValue.TryParse(cookieHeaderValue2, out setCookieHeaderValue2); Assert.Equal(setCookieHeaderValue1, setCookieHeaderValue2); }
/// <summary> /// Add a new cookie /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="options"></param> public void Append(string key, string value, CookieOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } var setCookieHeaderValue = new SetCookieHeaderValue( UrlEncoder.Default.Encode(key), UrlEncoder.Default.Encode(value)) { Domain = options.Domain, Path = options.Path, Expires = options.Expires, Secure = options.Secure, HttpOnly = options.HttpOnly, }; Headers[HeaderNames.SetCookie] = StringValues.Concat(Headers[HeaderNames.SetCookie], setCookieHeaderValue.ToString()); }
public void SetCookieHeaderValue_ToString_SameSiteNoneCompat() { SetCookieHeaderValue.SuppressSameSiteNone = true; var input = new SetCookieHeaderValue("name", "value") { SameSite = SameSiteMode.None, }; Assert.Equal("name=value", input.ToString()); SetCookieHeaderValue.SuppressSameSiteNone = false; var input2 = new SetCookieHeaderValue("name", "value") { SameSite = SameSiteMode.None, }; Assert.Equal("name=value; samesite=none", input2.ToString()); }
public void SetCookieHeaderValue_TryParse_AcceptsValidValues_SameSiteNoneCompat() { SetCookieHeaderValue.SuppressSameSiteNone = true; Assert.True(SetCookieHeaderValue.TryParse("name=value; samesite=none", out var header)); var cookie = new SetCookieHeaderValue("name", "value") { SameSite = SameSiteMode.Strict, }; Assert.Equal(cookie, header); Assert.Equal("name=value; samesite=strict", header.ToString()); SetCookieHeaderValue.SuppressSameSiteNone = false; Assert.True(SetCookieHeaderValue.TryParse("name=value; samesite=none", out var header2)); var cookie2 = new SetCookieHeaderValue("name", "value") { SameSite = SameSiteMode.None, }; Assert.Equal(cookie2, header2); Assert.Equal("name=value; samesite=none", header2.ToString()); }
public void SetCookieHeaderValue_AppendToStringBuilder_SameSiteNoneCompat() { SetCookieHeaderValue.SuppressSameSiteNone = true; var builder = new StringBuilder(); var input = new SetCookieHeaderValue("name", "value") { SameSite = SameSiteMode.None, }; input.AppendToStringBuilder(builder); Assert.Equal("name=value", builder.ToString()); SetCookieHeaderValue.SuppressSameSiteNone = false; var builder2 = new StringBuilder(); var input2 = new SetCookieHeaderValue("name", "value") { SameSite = SameSiteMode.None, }; input2.AppendToStringBuilder(builder2); Assert.Equal("name=value; samesite=none", builder2.ToString()); }
public void SetCookieHeaderValue_ToString(SetCookieHeaderValue input, string expectedValue) { Assert.Equal(expectedValue, input.ToString()); }
// name=value; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1; path=path1; secure; samesite={Strict|Lax}; httponly private static int GetSetCookieLength(StringSegment input, int startIndex, out SetCookieHeaderValue parsedValue) { Contract.Requires(startIndex >= 0); var offset = startIndex; parsedValue = null; if (StringSegment.IsNullOrEmpty(input) || (offset >= input.Length)) { return(0); } var result = new SetCookieHeaderValue(); // The caller should have already consumed any leading whitespace, commas, etc.. // Name=value; // Name var itemLength = HttpRuleParser.GetTokenLength(input, offset); if (itemLength == 0) { return(0); } result._name = input.Subsegment(offset, itemLength); offset += itemLength; // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return(0); } // value or "quoted value" // The value may be empty result._value = CookieHeaderValue.GetCookieValue(input, ref offset); // *(';' SP cookie-av) while (offset < input.Length) { if (input[offset] == ',') { // Divider between headers break; } if (input[offset] != ';') { // Expecting a ';' between parameters return(0); } offset++; offset += HttpRuleParser.GetWhitespaceLength(input, offset); // cookie-av = expires-av / max-age-av / domain-av / path-av / secure-av / samesite-av / httponly-av / extension-av itemLength = HttpRuleParser.GetTokenLength(input, offset); if (itemLength == 0) { // Trailing ';' or leading into garbage. Let the next parser fail. break; } var token = input.Subsegment(offset, itemLength); offset += itemLength; // expires-av = "Expires=" sane-cookie-date if (StringSegment.Equals(token, ExpiresToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return(0); } var dateString = ReadToSemicolonOrEnd(input, ref offset); DateTimeOffset expirationDate; if (!HttpRuleParser.TryStringToDate(dateString, out expirationDate)) { // Invalid expiration date, abort return(0); } result.Expires = expirationDate; } // max-age-av = "Max-Age=" non-zero-digit *DIGIT else if (StringSegment.Equals(token, MaxAgeToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return(0); } itemLength = HttpRuleParser.GetNumberLength(input, offset, allowDecimal: false); if (itemLength == 0) { return(0); } var numberString = input.Subsegment(offset, itemLength); long maxAge; if (!HeaderUtilities.TryParseNonNegativeInt64(numberString, out maxAge)) { // Invalid expiration date, abort return(0); } result.MaxAge = TimeSpan.FromSeconds(maxAge); offset += itemLength; } // domain-av = "Domain=" domain-value // domain-value = <subdomain> ; defined in [RFC1034], Section 3.5, as enhanced by [RFC1123], Section 2.1 else if (StringSegment.Equals(token, DomainToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return(0); } // We don't do any detailed validation on the domain. result.Domain = ReadToSemicolonOrEnd(input, ref offset); } // path-av = "Path=" path-value // path-value = <any CHAR except CTLs or ";"> else if (StringSegment.Equals(token, PathToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return(0); } // We don't do any detailed validation on the path. result.Path = ReadToSemicolonOrEnd(input, ref offset); } // secure-av = "Secure" else if (StringSegment.Equals(token, SecureToken, StringComparison.OrdinalIgnoreCase)) { result.Secure = true; } // samesite-av = "SameSite" / "SameSite=" samesite-value // samesite-value = "Strict" / "Lax" else if (StringSegment.Equals(token, SameSiteToken, StringComparison.OrdinalIgnoreCase)) { if (!ReadEqualsSign(input, ref offset)) { result.SameSite = SameSiteMode.Strict; } else { var enforcementMode = ReadToSemicolonOrEnd(input, ref offset); if (StringSegment.Equals(enforcementMode, SameSiteLaxToken, StringComparison.OrdinalIgnoreCase)) { result.SameSite = SameSiteMode.Lax; } else { result.SameSite = SameSiteMode.Strict; } } } // httponly-av = "HttpOnly" else if (StringSegment.Equals(token, HttpOnlyToken, StringComparison.OrdinalIgnoreCase)) { result.HttpOnly = true; } // extension-av = <any CHAR except CTLs or ";"> else { // TODO: skip it? Store it in a list? } } parsedValue = result; return(offset - startIndex); }
/// <inheritdoc /> public void Append(string key, string value, CookieOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } var setCookieHeaderValue = new SetCookieHeaderValue( Uri.EscapeDataString(key), Uri.EscapeDataString(value)) { Domain = options.Domain, Path = options.Path, Expires = options.Expires, Secure = options.Secure, HttpOnly = options.HttpOnly, }; string cookieValue; if (_builderPool == null) { cookieValue = setCookieHeaderValue.ToString(); } else { var stringBuilder = _builderPool.Get(); try { setCookieHeaderValue.AppendToStringBuilder(stringBuilder); cookieValue = stringBuilder.ToString(); } finally { _builderPool.Return(stringBuilder); } } Headers[HeaderNames.SetCookie] = StringValues.Concat(Headers[HeaderNames.SetCookie], cookieValue); }
public void SetCookieHeaderValue_Parse_AcceptsValidValues(SetCookieHeaderValue cookie, string expectedValue) { var header = SetCookieHeaderValue.Parse(expectedValue); Assert.Equal(cookie, header); Assert.Equal(expectedValue, header.ToString()); }
public void SetCookieHeaderValue_Value() { var cookie = new SetCookieHeaderValue("name"); Assert.Equal(String.Empty, cookie.Value); cookie.Value = "value1"; Assert.Equal("value1", cookie.Value); }
public void SetCookieHeaderValue_Ctor1_InitializesCorrectly() { var header = new SetCookieHeaderValue("cookie"); Assert.Equal("cookie", header.Name); Assert.Equal(string.Empty, header.Value); }
/// <summary> /// Appends a new response cookie to the Set-Cookie header. If the cookie is larger than the given size limit /// then it will be broken down into multiple cookies as follows: /// Set-Cookie: CookieName=chunks:3; path=/ /// Set-Cookie: CookieNameC1=Segment1; path=/ /// Set-Cookie: CookieNameC2=Segment2; path=/ /// Set-Cookie: CookieNameC3=Segment3; path=/ /// </summary> /// <param name="context"></param> /// <param name="key"></param> /// <param name="value"></param> /// <param name="options"></param> public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var escapedKey = Encoder.UrlEncode(key); var template = new SetCookieHeaderValue(escapedKey) { Domain = options.Domain, Expires = options.Expires, HttpOnly = options.HttpOnly, Path = options.Path, Secure = options.Secure, }; var templateLength = template.ToString().Length; value = value ?? string.Empty; var quoted = false; if (IsQuoted(value)) { quoted = true; value = RemoveQuotes(value); } var escapedValue = Encoder.UrlEncode(value); // Normal cookie var responseHeaders = context.Response.Headers; if (!ChunkSize.HasValue || ChunkSize.Value > templateLength + escapedValue.Length + (quoted ? 2 : 0)) { template.Value = quoted ? Quote(escapedValue) : escapedValue; responseHeaders.Append(Constants.Headers.SetCookie, template.ToString()); } else if (ChunkSize.Value < templateLength + (quoted ? 2 : 0) + 10) { // 10 is the minimum data we want to put in an individual cookie, including the cookie chunk identifier "CXX". // No room for data, we can't chunk the options and name throw new InvalidOperationException(Resources.Exception_CookieLimitTooSmall); } else { // Break the cookie down into multiple cookies. // Key = CookieName, value = "Segment1Segment2Segment2" // Set-Cookie: CookieName=chunks:3; path=/ // Set-Cookie: CookieNameC1="Segment1"; path=/ // Set-Cookie: CookieNameC2="Segment2"; path=/ // Set-Cookie: CookieNameC3="Segment3"; path=/ var dataSizePerCookie = ChunkSize.Value - templateLength - (quoted ? 2 : 0) - 3; // Budget 3 chars for the chunkid. var cookieChunkCount = (int)Math.Ceiling(escapedValue.Length * 1.0 / dataSizePerCookie); template.Value = "chunks:" + cookieChunkCount.ToString(CultureInfo.InvariantCulture); responseHeaders.Append(Constants.Headers.SetCookie, template.ToString()); var chunks = new string[cookieChunkCount]; var offset = 0; for (var chunkId = 1; chunkId <= cookieChunkCount; chunkId++) { var remainingLength = escapedValue.Length - offset; var length = Math.Min(dataSizePerCookie, remainingLength); var segment = escapedValue.Substring(offset, length); offset += length; template.Name = escapedKey + "C" + chunkId.ToString(CultureInfo.InvariantCulture); template.Value = quoted ? Quote(segment) : segment; chunks[chunkId - 1] = template.ToString(); } responseHeaders.Append(Constants.Headers.SetCookie, chunks); } }
/// <summary> /// Initializes a new instance of the <see cref="ResponseCookieTestBuilder"/> class. /// </summary> public ResponseCookieTestBuilder() { this.validations = new List<Func<SetCookieHeaderValue, SetCookieHeaderValue, bool>>(); this.responseCookie = new SetCookieHeaderValue(FakeCookieName); }
public void SetCookieHeaderValue_Parse_RejectsInvalidValues(string value) { Assert.Throws <FormatException>(() => SetCookieHeaderValue.Parse(value)); }
public void SetCookieHeaderValue_TryParse_RejectsInvalidValues(string value) { Assert.False(SetCookieHeaderValue.TryParse(value, out var _)); }
/// <summary> /// Appends a new response cookie to the Set-Cookie header. If the cookie is larger than the given size limit /// then it will be broken down into multiple cookies as follows: /// Set-Cookie: CookieName=chunks-3; path=/ /// Set-Cookie: CookieNameC1=Segment1; path=/ /// Set-Cookie: CookieNameC2=Segment2; path=/ /// Set-Cookie: CookieNameC3=Segment3; path=/ /// </summary> /// <param name="context"></param> /// <param name="key"></param> /// <param name="value"></param> /// <param name="options"></param> public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var template = new SetCookieHeaderValue(key) { Domain = options.Domain, Expires = options.Expires, HttpOnly = options.HttpOnly, Path = options.Path, Secure = options.Secure, }; var templateLength = template.ToString().Length; value = value ?? string.Empty; // Normal cookie var responseCookies = context.Response.Cookies; if (!ChunkSize.HasValue || ChunkSize.Value > templateLength + value.Length) { responseCookies.Append(key, value, options); } else if (ChunkSize.Value < templateLength + 10) { // 10 is the minimum data we want to put in an individual cookie, including the cookie chunk identifier "CXX". // No room for data, we can't chunk the options and name throw new InvalidOperationException(Resources.Exception_CookieLimitTooSmall); } else { // Break the cookie down into multiple cookies. // Key = CookieName, value = "Segment1Segment2Segment2" // Set-Cookie: CookieName=chunks-3; path=/ // Set-Cookie: CookieNameC1="Segment1"; path=/ // Set-Cookie: CookieNameC2="Segment2"; path=/ // Set-Cookie: CookieNameC3="Segment3"; path=/ var dataSizePerCookie = ChunkSize.Value - templateLength - 3; // Budget 3 chars for the chunkid. var cookieChunkCount = (int)Math.Ceiling(value.Length * 1.0 / dataSizePerCookie); responseCookies.Append(key, ChunkCountPrefix + cookieChunkCount.ToString(CultureInfo.InvariantCulture), options); var offset = 0; for (var chunkId = 1; chunkId <= cookieChunkCount; chunkId++) { var remainingLength = value.Length - offset; var length = Math.Min(dataSizePerCookie, remainingLength); var segment = value.Substring(offset, length); offset += length; responseCookies.Append(key + ChunkKeySuffix + chunkId.ToString(CultureInfo.InvariantCulture), segment, options); } } }
public void SetCookieHeaderValue_ParseStrictList_AcceptsValidValues(IList <SetCookieHeaderValue> cookies, string[] input) { var results = SetCookieHeaderValue.ParseStrictList(input); Assert.Equal(cookies, results); }
public void SetCookieHeaderValue_ParseStrictList_ThrowsForAnyInvalidValues(IList <SetCookieHeaderValue> cookies, string[] input) { Assert.Throws <FormatException>(() => SetCookieHeaderValue.ParseStrictList(input)); }
public void SetCookieHeaderValue_Ctor2InitializesCorrectly(string name, string value) { var header = new SetCookieHeaderValue(name, value); Assert.Equal(name, header.Name); Assert.Equal(value, header.Value); }
public static bool TryParse(string input, out SetCookieHeaderValue parsedValue) { var index = 0; return SingleValueParser.TryParseValue(input, ref index, out parsedValue); }
// name=value; expires=Sun, 06 Nov 1994 08:49:37 GMT; max-age=86400; domain=domain1; path=path1; secure; httponly private static int GetSetCookieLength(string input, int startIndex, out SetCookieHeaderValue parsedValue) { Contract.Requires(startIndex >= 0); var offset = startIndex; parsedValue = null; if (string.IsNullOrEmpty(input) || (offset >= input.Length)) { return 0; } var result = new SetCookieHeaderValue(); // The caller should have already consumed any leading whitespace, commas, etc.. // Name=value; // Name var itemLength = HttpRuleParser.GetTokenLength(input, offset); if (itemLength == 0) { return 0; } result._name = input.Substring(offset, itemLength); offset += itemLength; // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return 0; } string value; // value or "quoted value" itemLength = CookieHeaderValue.GetCookieValueLength(input, offset, out value); // The value may be empty result._value = input.Substring(offset, itemLength); offset += itemLength; // *(';' SP cookie-av) while (offset < input.Length) { if (input[offset] == ',') { // Divider between headers break; } if (input[offset] != ';') { // Expecting a ';' between parameters return 0; } offset++; offset += HttpRuleParser.GetWhitespaceLength(input, offset); // cookie-av = expires-av / max-age-av / domain-av / path-av / secure-av / httponly-av / extension-av itemLength = HttpRuleParser.GetTokenLength(input, offset); if (itemLength == 0) { // Trailing ';' or leading into garbage. Let the next parser fail. break; } var token = input.Substring(offset, itemLength); offset += itemLength; // expires-av = "Expires=" sane-cookie-date if (string.Equals(token, ExpiresToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return 0; } var dateString = ReadToSemicolonOrEnd(input, ref offset); DateTimeOffset expirationDate; if (!HttpRuleParser.TryStringToDate(dateString, out expirationDate)) { // Invalid expiration date, abort return 0; } result.Expires = expirationDate; } // max-age-av = "Max-Age=" non-zero-digit *DIGIT else if (string.Equals(token, MaxAgeToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return 0; } itemLength = HttpRuleParser.GetNumberLength(input, offset, allowDecimal: false); if (itemLength == 0) { return 0; } var numberString = input.Substring(offset, itemLength); long maxAge; if (!HeaderUtilities.TryParseInt64(numberString, out maxAge)) { // Invalid expiration date, abort return 0; } result.MaxAge = TimeSpan.FromSeconds(maxAge); offset += itemLength; } // domain-av = "Domain=" domain-value // domain-value = <subdomain> ; defined in [RFC1034], Section 3.5, as enhanced by [RFC1123], Section 2.1 else if (string.Equals(token, DomainToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return 0; } // We don't do any detailed validation on the domain. result.Domain = ReadToSemicolonOrEnd(input, ref offset); } // path-av = "Path=" path-value // path-value = <any CHAR except CTLs or ";"> else if (string.Equals(token, PathToken, StringComparison.OrdinalIgnoreCase)) { // = (no spaces) if (!ReadEqualsSign(input, ref offset)) { return 0; } // We don't do any detailed validation on the path. result.Path = ReadToSemicolonOrEnd(input, ref offset); } // secure-av = "Secure" else if (string.Equals(token, SecureToken, StringComparison.OrdinalIgnoreCase)) { result.Secure = true; } // httponly-av = "HttpOnly" else if (string.Equals(token, HttpOnlyToken, StringComparison.OrdinalIgnoreCase)) { result.HttpOnly = true; } // extension-av = <any CHAR except CTLs or ";"> else { // TODO: skip it? Store it in a list? } } parsedValue = result; return offset - startIndex; }
public void SetCookieHeaderValue_TryParse_AcceptsValidValues(SetCookieHeaderValue cookie, string expectedValue) { SetCookieHeaderValue header; bool result = SetCookieHeaderValue.TryParse(expectedValue, out header); Assert.True(result); Assert.Equal(cookie, header); Assert.Equal(expectedValue, header.ToString()); }
public static bool TryParse(StringSegment input, out SetCookieHeaderValue parsedValue) { var index = 0; return(SingleValueParser.TryParseValue(input, ref index, out parsedValue)); }