Code cleanup.

This commit is contained in:
Chris Ross 2014-09-15 09:35:55 -07:00
parent 07b3fe2135
commit 35ad3ec7bb
6 changed files with 54 additions and 77 deletions

View File

@ -1,8 +1,8 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.MemoryCache;
using Microsoft.AspNet.Security; using Microsoft.AspNet.Security;
using Microsoft.AspNet.Security.Cookies.Infrastructure; using Microsoft.AspNet.Security.Cookies.Infrastructure;
using Microsoft.Framework.Cache.Memory;
namespace CookieSessionSample namespace CookieSessionSample
{ {
@ -33,7 +33,7 @@ namespace CookieSessionSample
{ {
context.SetAbsoluteExpiration(expiresUtc.Value); context.SetAbsoluteExpiration(expiresUtc.Value);
} }
context.SetSlidingExpiraiton(TimeSpan.FromHours(1)); // TODO: configurable. context.SetSlidingExpiration(TimeSpan.FromHours(1)); // TODO: configurable.
return (AuthenticationTicket)context.State; return (AuthenticationTicket)context.State;
}); });

View File

@ -17,7 +17,7 @@ namespace CookieSessionSample
app.Run(async context => app.Run(async context =>
{ {
if (context.User == null || !context.User.Identity.IsAuthenticated) if (context.User.Identity == null || !context.User.Identity.IsAuthenticated)
{ {
// Make a large identity // Make a large identity
var claims = new List<Claim>(1001); var claims = new List<Claim>(1001);

View File

@ -4,12 +4,12 @@
"Microsoft.AspNet.Hosting": "1.0.0-*", "Microsoft.AspNet.Hosting": "1.0.0-*",
"Microsoft.AspNet.Http": "1.0.0-*", "Microsoft.AspNet.Http": "1.0.0-*",
"Microsoft.AspNet.HttpFeature": "1.0.0-*", "Microsoft.AspNet.HttpFeature": "1.0.0-*",
"Microsoft.AspNet.MemoryCache": "1.0.0-*",
"Microsoft.AspNet.PipelineCore": "1.0.0-*", "Microsoft.AspNet.PipelineCore": "1.0.0-*",
"Microsoft.AspNet.RequestContainer": "1.0.0-*", "Microsoft.AspNet.RequestContainer": "1.0.0-*",
"Microsoft.AspNet.Security": "1.0.0-*", "Microsoft.AspNet.Security": "1.0.0-*",
"Microsoft.AspNet.Security.Cookies": "1.0.0-*", "Microsoft.AspNet.Security.Cookies": "1.0.0-*",
"Microsoft.AspNet.Server.WebListener": "1.0.0-*", "Microsoft.AspNet.Server.WebListener": "1.0.0-*",
"Microsoft.Framework.Cache.Memory": "1.0.0-*",
"Microsoft.Framework.DependencyInjection": "1.0.0-*" "Microsoft.Framework.DependencyInjection": "1.0.0-*"
}, },
"commands": { "web": "Microsoft.AspNet.Hosting server=Microsoft.AspNet.Server.WebListener server.urls=http://localhost:12345" }, "commands": { "web": "Microsoft.AspNet.Hosting server=Microsoft.AspNet.Server.WebListener server.urls=http://localhost:12345" },

View File

@ -63,7 +63,7 @@ namespace Microsoft.AspNet.Security.Cookies
Claim claim = ticket.Identity.Claims.FirstOrDefault(c => c.Type.Equals(SessionIdClaim)); Claim claim = ticket.Identity.Claims.FirstOrDefault(c => c.Type.Equals(SessionIdClaim));
if (claim == null) if (claim == null)
{ {
_logger.WriteWarning(@"SessoinId missing"); _logger.WriteWarning(@"SessionId missing");
return null; return null;
} }
_sessionKey = claim.Value; _sessionKey = claim.Value;

View File

@ -4,7 +4,6 @@
using System; using System;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Security.Cookies.Infrastructure; using Microsoft.AspNet.Security.Cookies.Infrastructure;
using Microsoft.AspNet.Security.DataHandler; using Microsoft.AspNet.Security.DataHandler;
using Microsoft.AspNet.Security.DataProtection; using Microsoft.AspNet.Security.DataProtection;

View File

@ -17,6 +17,8 @@ namespace Microsoft.AspNet.Security.Cookies.Infrastructure
{ {
public ChunkingCookieManager() 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/.
ChunkSize = 4090; ChunkSize = 4090;
ThrowForPartialCookies = true; ThrowForPartialCookies = true;
} }
@ -40,9 +42,8 @@ namespace Microsoft.AspNet.Security.Cookies.Infrastructure
{ {
if (value != null && value.StartsWith("chunks:", StringComparison.Ordinal)) if (value != null && value.StartsWith("chunks:", StringComparison.Ordinal))
{ {
string chunksCountString = value.Substring("chunks:".Length); var chunksCountString = value.Substring("chunks:".Length);
int chunksCount; if (int.TryParse(chunksCountString, NumberStyles.None, CultureInfo.InvariantCulture, out var chunksCount))
if (int.TryParse(chunksCountString, NumberStyles.None, CultureInfo.InvariantCulture, out chunksCount))
{ {
return chunksCount; return chunksCount;
} }
@ -57,28 +58,23 @@ namespace Microsoft.AspNet.Security.Cookies.Infrastructure
/// <param name="context"></param> /// <param name="context"></param>
/// <param name="key"></param> /// <param name="key"></param>
/// <returns>The reassembled cookie, if any, or null.</returns> /// <returns>The reassembled cookie, if any, or null.</returns>
public string GetRequestCookie(HttpContext context, string key) public string GetRequestCookie([NotNull] HttpContext context, [NotNull] string key)
{ {
if (context == null) var requestCookies = context.Request.Cookies;
{ var value = requestCookies[key];
throw new ArgumentNullException("context"); var chunksCount = ParseChunksCount(value);
}
IReadableStringCollection requestCookies = context.Request.Cookies;
string value = requestCookies[key];
int chunksCount = ParseChunksCount(value);
if (chunksCount > 0) if (chunksCount > 0)
{ {
bool quoted = false; var quoted = false;
string[] chunks = new string[chunksCount]; var chunks = new string[chunksCount];
for (int chunkId = 1; chunkId <= chunksCount; chunkId++) for (var chunkId = 1; chunkId <= chunksCount; chunkId++)
{ {
string chunk = requestCookies[key + "C" + chunkId.ToString(CultureInfo.InvariantCulture)]; var chunk = requestCookies[key + "C" + chunkId.ToString(CultureInfo.InvariantCulture)];
if (chunk == null) if (chunk == null)
{ {
if (ThrowForPartialCookies) if (ThrowForPartialCookies)
{ {
int totalSize = 0; var totalSize = 0;
for (int i = 0; i < chunkId - 1; i++) for (int i = 0; i < chunkId - 1; i++)
{ {
totalSize += chunks[i].Length; totalSize += chunks[i].Length;
@ -97,7 +93,7 @@ namespace Microsoft.AspNet.Security.Cookies.Infrastructure
} }
chunks[chunkId - 1] = chunk; chunks[chunkId - 1] = chunk;
} }
string merged = string.Join(string.Empty, chunks); var merged = string.Join(string.Empty, chunks);
if (quoted) if (quoted)
{ {
merged = Quote(merged); merged = Quote(merged);
@ -119,25 +115,16 @@ namespace Microsoft.AspNet.Security.Cookies.Infrastructure
/// <param name="key"></param> /// <param name="key"></param>
/// <param name="value"></param> /// <param name="value"></param>
/// <param name="options"></param> /// <param name="options"></param>
public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options) public void AppendResponseCookie([NotNull] HttpContext context, [NotNull] string key, string value, [NotNull] CookieOptions options)
{ {
if (context == null) var domainHasValue = !string.IsNullOrEmpty(options.Domain);
{ var pathHasValue = !string.IsNullOrEmpty(options.Path);
throw new ArgumentNullException("context"); var expiresHasValue = options.Expires.HasValue;
}
if (options == null)
{
throw new ArgumentNullException("options");
}
bool domainHasValue = !string.IsNullOrEmpty(options.Domain); var escapedKey = Uri.EscapeDataString(key);
bool pathHasValue = !string.IsNullOrEmpty(options.Path); var prefix = escapedKey + "=";
bool expiresHasValue = options.Expires.HasValue;
string escapedKey = Uri.EscapeDataString(key); var suffix = string.Concat(
string prefix = escapedKey + "=";
string suffix = string.Concat(
!domainHasValue ? null : "; domain=", !domainHasValue ? null : "; domain=",
!domainHasValue ? null : options.Domain, !domainHasValue ? null : options.Domain,
!pathHasValue ? null : "; path=", !pathHasValue ? null : "; path=",
@ -148,19 +135,19 @@ namespace Microsoft.AspNet.Security.Cookies.Infrastructure
!options.HttpOnly ? null : "; HttpOnly"); !options.HttpOnly ? null : "; HttpOnly");
value = value ?? string.Empty; value = value ?? string.Empty;
bool quoted = false; var quoted = false;
if (IsQuoted(value)) if (IsQuoted(value))
{ {
quoted = true; quoted = true;
value = RemoveQuotes(value); value = RemoveQuotes(value);
} }
string escapedValue = Uri.EscapeDataString(value); var escapedValue = Uri.EscapeDataString(value);
// Normal cookie // Normal cookie
IHeaderDictionary responseHeaders = context.Response.Headers; var responseHeaders = context.Response.Headers;
if (!ChunkSize.HasValue || ChunkSize.Value > prefix.Length + escapedValue.Length + suffix.Length + (quoted ? 2 : 0)) if (!ChunkSize.HasValue || ChunkSize.Value > prefix.Length + escapedValue.Length + suffix.Length + (quoted ? 2 : 0))
{ {
string setCookieValue = string.Concat( var setCookieValue = string.Concat(
prefix, prefix,
quoted ? Quote(escapedValue) : escapedValue, quoted ? Quote(escapedValue) : escapedValue,
suffix); suffix);
@ -180,18 +167,18 @@ namespace Microsoft.AspNet.Security.Cookies.Infrastructure
// Set-Cookie: CookieNameC1="Segment1"; path=/ // Set-Cookie: CookieNameC1="Segment1"; path=/
// Set-Cookie: CookieNameC2="Segment2"; path=/ // Set-Cookie: CookieNameC2="Segment2"; path=/
// Set-Cookie: CookieNameC3="Segment3"; path=/ // Set-Cookie: CookieNameC3="Segment3"; path=/
int dataSizePerCookie = ChunkSize.Value - prefix.Length - suffix.Length - (quoted ? 2 : 0) - 3; // Budget 3 chars for the chunkid. var dataSizePerCookie = ChunkSize.Value - prefix.Length - suffix.Length - (quoted ? 2 : 0) - 3; // Budget 3 chars for the chunkid.
int cookieChunkCount = (int)Math.Ceiling(escapedValue.Length * 1.0 / dataSizePerCookie); var cookieChunkCount = (int)Math.Ceiling(escapedValue.Length * 1.0 / dataSizePerCookie);
responseHeaders.AppendValues(Constants.Headers.SetCookie, prefix + "chunks:" + cookieChunkCount.ToString(CultureInfo.InvariantCulture) + suffix); responseHeaders.AppendValues(Constants.Headers.SetCookie, prefix + "chunks:" + cookieChunkCount.ToString(CultureInfo.InvariantCulture) + suffix);
string[] chunks = new string[cookieChunkCount]; var chunks = new string[cookieChunkCount];
int offset = 0; var offset = 0;
for (int chunkId = 1; chunkId <= cookieChunkCount; chunkId++) for (var chunkId = 1; chunkId <= cookieChunkCount; chunkId++)
{ {
int remainingLength = escapedValue.Length - offset; var remainingLength = escapedValue.Length - offset;
int length = Math.Min(dataSizePerCookie, remainingLength); var length = Math.Min(dataSizePerCookie, remainingLength);
string segment = escapedValue.Substring(offset, length); var segment = escapedValue.Substring(offset, length);
offset += length; offset += length;
chunks[chunkId - 1] = string.Concat( chunks[chunkId - 1] = string.Concat(
@ -215,34 +202,25 @@ namespace Microsoft.AspNet.Security.Cookies.Infrastructure
/// <param name="context"></param> /// <param name="context"></param>
/// <param name="key"></param> /// <param name="key"></param>
/// <param name="options"></param> /// <param name="options"></param>
public void DeleteCookie(HttpContext context, string key, CookieOptions options) public void DeleteCookie([NotNull] HttpContext context, [NotNull] string key, [NotNull] CookieOptions options)
{ {
if (context == null) var escapedKey = Uri.EscapeDataString(key);
{ var keys = new List<string>();
throw new ArgumentNullException("context");
}
if (options == null)
{
throw new ArgumentNullException("options");
}
string escapedKey = Uri.EscapeDataString(key);
List<string> keys = new List<string>();
keys.Add(escapedKey + "="); keys.Add(escapedKey + "=");
string requestCookie = context.Request.Cookies[key]; var requestCookie = context.Request.Cookies[key];
int chunks = ParseChunksCount(requestCookie); var chunks = ParseChunksCount(requestCookie);
if (chunks > 0) if (chunks > 0)
{ {
for (int i = 1; i <= chunks + 1; i++) for (int i = 1; i <= chunks + 1; i++)
{ {
string subkey = escapedKey + "C" + i.ToString(CultureInfo.InvariantCulture); var subkey = escapedKey + "C" + i.ToString(CultureInfo.InvariantCulture);
keys.Add(subkey + "="); keys.Add(subkey + "=");
} }
} }
bool domainHasValue = !string.IsNullOrEmpty(options.Domain); var domainHasValue = !string.IsNullOrEmpty(options.Domain);
bool pathHasValue = !string.IsNullOrEmpty(options.Path); var pathHasValue = !string.IsNullOrEmpty(options.Path);
Func<string, bool> rejectPredicate; Func<string, bool> rejectPredicate;
Func<string, bool> predicate = value => keys.Any(k => value.StartsWith(k, StringComparison.OrdinalIgnoreCase)); Func<string, bool> predicate = value => keys.Any(k => value.StartsWith(k, StringComparison.OrdinalIgnoreCase));
@ -259,8 +237,8 @@ namespace Microsoft.AspNet.Security.Cookies.Infrastructure
rejectPredicate = value => predicate(value); rejectPredicate = value => predicate(value);
} }
IHeaderDictionary responseHeaders = context.Response.Headers; var responseHeaders = context.Response.Headers;
IList<string> existingValues = responseHeaders.GetValues(Constants.Headers.SetCookie); var existingValues = responseHeaders.GetValues(Constants.Headers.SetCookie);
if (existingValues != null) if (existingValues != null)
{ {
responseHeaders.SetValues(Constants.Headers.SetCookie, existingValues.Where(value => !rejectPredicate(value)).ToArray()); responseHeaders.SetValues(Constants.Headers.SetCookie, existingValues.Where(value => !rejectPredicate(value)).ToArray());
@ -270,7 +248,7 @@ namespace Microsoft.AspNet.Security.Cookies.Infrastructure
context, context,
key, key,
string.Empty, string.Empty,
new CookieOptions new CookieOptions()
{ {
Path = options.Path, Path = options.Path,
Domain = options.Domain, Domain = options.Domain,
@ -283,7 +261,7 @@ namespace Microsoft.AspNet.Security.Cookies.Infrastructure
context, context,
key + "C" + i.ToString(CultureInfo.InvariantCulture), key + "C" + i.ToString(CultureInfo.InvariantCulture),
string.Empty, string.Empty,
new CookieOptions new CookieOptions()
{ {
Path = options.Path, Path = options.Path,
Domain = options.Domain, Domain = options.Domain,
@ -292,17 +270,17 @@ namespace Microsoft.AspNet.Security.Cookies.Infrastructure
} }
} }
private static bool IsQuoted(string value) private static bool IsQuoted([NotNull] string value)
{ {
return value.Length >= 2 && value[0] == '"' && value[value.Length - 1] == '"'; return value.Length >= 2 && value[0] == '"' && value[value.Length - 1] == '"';
} }
private static string RemoveQuotes(string value) private static string RemoveQuotes([NotNull] string value)
{ {
return value.Substring(1, value.Length - 2); return value.Substring(1, value.Length - 2);
} }
private static string Quote(string value) private static string Quote([NotNull] string value)
{ {
return '"' + value + '"'; return '"' + value + '"';
} }