Skip to content

Commit

Permalink
Fix for use of httpcontext
Browse files Browse the repository at this point in the history
  • Loading branch information
nemi-chand committed Mar 16, 2023
1 parent 903fd9d commit d434dda
Show file tree
Hide file tree
Showing 4 changed files with 113 additions and 42 deletions.
16 changes: 9 additions & 7 deletions src/CookieManager/CookieManager.csproj
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<!--<TargetFramework>netcoreapp1.0</TargetFramework>-->
<TargetFrameworks>netstandard1.6;netstandard2.0</TargetFrameworks>
<RepositoryUrl>https://github.com/nemi-chand/CookieManager</RepositoryUrl>
<PackageProjectUrl>https://github.com/nemi-chand/CookieManager</PackageProjectUrl>
<Description>ASP.Net Core Abstraction layer on top of Http Cookie</Description>
<Authors>Nemi Chand</Authors>
<Title>CookieManager : ASP.Net Core Abstraction layer on top of Http Cookie</Title>
<Version>2.0.0</Version>
<Version>2.0.1</Version>
<NeutralLanguage>en</NeutralLanguage>
<PackageTags>Cookie Manager,asp.net core cookie,cookie,http cookie,secure cookie</PackageTags>
<PackageReleaseNotes>Added support netstandard 1.6 and netstandard 2.0</PackageReleaseNotes>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
<FileVersion>2.0.0.0</FileVersion>
<PackageReleaseNotes>Bux fix related to httpcontext</PackageReleaseNotes>
<AssemblyVersion>2.0.1.0</AssemblyVersion>
<FileVersion>2.0.1.0</FileVersion>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageLicenseUrl>https://github.com/nemi-chand/CookieManager/blob/master/LICENSE</PackageLicenseUrl>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
</PropertyGroup>

<PropertyGroup Condition=" '$(TargetFramework)' == 'netcoreapp1.0' ">
Expand All @@ -31,8 +31,10 @@
<PackageReference Include="Microsoft.AspNetCore.Http" Version="1.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>


<ItemGroup>
<None Include="docs\README.md" Pack="true" PackagePath="\"/>
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
<PackageReference Include="Microsoft.AspNetCore.DataProtection" Version="2.0.0" />
Expand Down
62 changes: 30 additions & 32 deletions src/CookieManager/HttpCookie.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CookieManager
{
Expand All @@ -13,25 +11,25 @@ namespace CookieManager
/// </summary>
public class HttpCookie : ICookie
{
private readonly HttpContext _httpContext;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IDataProtector _dataProtector;
private static readonly string Purpose = "CookieManager.Token.v1";
private readonly CookieManagerOptions _cookieManagerOptions;
private readonly ChunkingHttpCookie _chunkingHttpCookie;



/// <summary>
/// External depedenacy of <see cref="IHttpContextAccessor" />
/// </summary>
/// <param name="httpAccessor">IHttpAccessor</param>
/// <param name="dataProtectionProvider">data protection provider</param>
/// <param name="optionAccessor">cookie manager option accessor</param>
public HttpCookie(IHttpContextAccessor httpAccessor,
/// <summary>
/// External depedenacy of <see cref="IHttpContextAccessor" />
/// </summary>
/// <param name="httpContextAccessor">IHttpAccessor</param>
/// <param name="dataProtectionProvider">data protection provider</param>
/// <param name="optionAccessor">cookie manager option accessor</param>
public HttpCookie(IHttpContextAccessor httpContextAccessor,
IDataProtectionProvider dataProtectionProvider,
IOptions<CookieManagerOptions> optionAccessor)
{
_httpContext = httpAccessor.HttpContext;
_httpContextAccessor = httpContextAccessor;
_dataProtector = dataProtectionProvider.CreateProtector(Purpose);
_cookieManagerOptions = optionAccessor.Value;
_chunkingHttpCookie = new ChunkingHttpCookie(optionAccessor);
Expand All @@ -41,28 +39,28 @@ public ICollection<string> Keys
{
get
{
if(_httpContext == null)
if(_httpContextAccessor.HttpContext == null)
{
throw new ArgumentNullException(nameof(_httpContext));
throw new ArgumentNullException(nameof(_httpContextAccessor.HttpContext));
}

return _httpContext.Request.Cookies.Keys;
return _httpContextAccessor.HttpContext.Request.Cookies.Keys;
}
}

public bool Contains(string key)
{
if(_httpContext == null)
if(_httpContextAccessor.HttpContext == null)
{
throw new ArgumentNullException(nameof(_httpContext));
throw new ArgumentNullException(nameof(_httpContextAccessor.HttpContext));
}

if(key == null)
{
throw new ArgumentNullException(nameof(key));
}

return _httpContext.Request.Cookies.ContainsKey(key);
return _httpContextAccessor.HttpContext.Request.Cookies.ContainsKey(key);
}

/// <summary>
Expand All @@ -72,9 +70,9 @@ public bool Contains(string key)
/// <returns>value</returns>
public string Get(string key)
{
if (_httpContext == null)
if (_httpContextAccessor.HttpContext == null)
{
throw new ArgumentNullException(nameof(_httpContext));
throw new ArgumentNullException(nameof(_httpContextAccessor.HttpContext));
}

if (key == null)
Expand All @@ -84,7 +82,7 @@ public string Get(string key)

if (Contains(key))
{
var encodedValue = _chunkingHttpCookie.GetRequestCookie(_httpContext, key);
var encodedValue = _chunkingHttpCookie.GetRequestCookie(_httpContextAccessor.HttpContext, key);
var protectedData = string.Empty;
//allow encryption is optional
//may change the allow encryption to avoid this first check if cookie value is able to decode than unprotect tha data
Expand All @@ -108,17 +106,17 @@ public string Get(string key)
/// <param name="key">Key</param>
public void Remove(string key)
{
if (_httpContext == null)
if (_httpContextAccessor.HttpContext == null)
{
throw new ArgumentNullException(nameof(_httpContext));
throw new ArgumentNullException(nameof(_httpContextAccessor.HttpContext));
}

if (key == null)
{
throw new ArgumentNullException(nameof(key));
}

_chunkingHttpCookie.RemoveCookie(_httpContext, key);
_chunkingHttpCookie.RemoveCookie(_httpContextAccessor.HttpContext, key);
}

/// <summary>
Expand All @@ -129,15 +127,15 @@ public void Remove(string key)
/// <param name="expireTime">Expire time (default time is 10 millisencond)</param>
public void Set(string key, string value, int? expireTime)
{
//validate input TODO
if (_httpContext == null)
//validate input
if (_httpContextAccessor.HttpContext == null)
{
throw new ArgumentNullException(nameof(_httpContext));
throw new ArgumentNullException(nameof(_httpContextAccessor.HttpContext));
}

if (key == null)
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
throw new ArgumentException(nameof(key));
}

Set(key, value, null, expireTime);
Expand All @@ -151,9 +149,9 @@ public void Set(string key, string value, int? expireTime)
/// <param name="option">CookieOption</param>
public void Set(string key, string value, CookieOptions option)
{
if(_httpContext == null)
if(_httpContextAccessor.HttpContext == null)
{
throw new ArgumentNullException(nameof(_httpContext));
throw new ArgumentNullException(nameof(_httpContextAccessor.HttpContext));
}

if(key == null)
Expand Down Expand Up @@ -186,12 +184,12 @@ private void Set(string key, string value, CookieOptions option, int? expireTime
{
string protecetedData = _dataProtector.Protect(value);
var encodedValue = Base64TextEncoder.Encode(protecetedData);
_chunkingHttpCookie.AppendResponseCookie(_httpContext, key, encodedValue, option);
_chunkingHttpCookie.AppendResponseCookie(_httpContextAccessor.HttpContext, key, encodedValue, option);
}
else
{
//just append the cookie
_chunkingHttpCookie.AppendResponseCookie(_httpContext, key, value, option);
_chunkingHttpCookie.AppendResponseCookie(_httpContextAccessor.HttpContext, key, value, option);
}

}
Expand Down
3 changes: 0 additions & 3 deletions src/CookieManager/ICookieManager.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CookieManager
{
Expand Down
74 changes: 74 additions & 0 deletions src/CookieManager/docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
## Cookie Manager Usages

### ICookieManager interface

```csharp
public class MyCookie
{
public string Id { get; set; }

public DateTime Date { get; set; }

public string Indentifier { get; set; }
}

// Get the myCookie object
MyCookie objFromCookie = _cookieManager.Get<MyCookie>("Key");

// Set the myCookie object
MyCookie cooObj= new MyCookie()
{
Id = Guid.NewGuid().ToString(),
Indentifier = "valueasgrsdgdf66514sdfgsd51d65s31g5dsg1rs5dg",
Date = DateTime.Now
};
_cookieManager.Set("Key", cooObj, 60);

// Get or set <T>
// CookieOption example
MyCookie myCook = _cookieManager.GetOrSet<MyCookie>("Key", () =>
{
// Write function to store output in cookie
return new MyCookie()
{
Id = Guid.NewGuid().ToString(),
Indentifier = "valueasgrsdgdf66514sdfgsd51d65s31g5dsg1rs5dg",
Date = DateTime.Now
};

}, new CookieOptions() { HttpOnly = true, Expires = DateTime.Now.AddDays(1) });

```
### ICookie interface

```csharp
// Gets a cookie item associated with key
_cookie.Get("Key");

// Sets the cookie
_cookie.Set("Key", "value here", new CookieOptions() { HttpOnly = true, Expires = DateTime.Now.AddDays(1) });

```

### Configure Option
Add CookieManager in startup class in Configure Service
```csharp
// Add CookieManager
services.AddCookieManager();

// or
// Add CookieManager with options
services.AddCookieManager(options =>
{
// Allow cookie data to encrypt by default it allow encryption
options.AllowEncryption = false;
// Throw if not all chunks of a cookie are available on a request for re-assembly.
options.ThrowForPartialCookies = true;
// Set null if not allow to devide in chunks
options.ChunkSize = null;
// Default Cookie expire time if expire time set to null of cookie
// Default time is 1 day to expire cookie
options.DefaultExpireTimeInDays = 10;
});
```

0 comments on commit d434dda

Please sign in to comment.