Coder Social home page Coder Social logo

cookiemanager's Introduction

Cookie Manager

ASP.Net Core Abstraction layer on top of Cookie . ASP.NET Core Wrapper to read and write the cookie.

License NuGet Package

Build Status

Build server Platform Status
AppVeyor Windows AppVeyor
Travis Linux / MacOS Build Status
Azure Pipelines Windows / Linux / MacOS Build Status

Give a Star! โญ

If you like or are using this project please give it a star. Thanks!

Features

  • Strongly Typed : CookieManager interface allows you to play with generic object. You don't have to care about casting or serialization.
  • Secure Cookie Data :The cookie data is protected with the machine key, using security algorithm. For more about data protection (https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/)
  • Configuration :There are easy options to configure CookieManager. Just add the CookieManager in Configure Service.
  • Func<TResult> support :Encapsulates a method, which returns a value of the type specified by the TResult parameter
  • Ease to use :The interfaces allows to ease use of read and write http cookie.

Nuget Package : https://www.nuget.org/packages/CookieManager/

Install-Package CookieManager

.NET CLI

dotnet add package CookieManager --version 2.0.0

Usages

ICookieManager interface

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

// 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

// 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;
});

cookiemanager's People

Contributors

dependabot[bot] avatar nemi-chand avatar nemi-chand-jat avatar nruizneiman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

cookiemanager's Issues

Newtonsoft.Json.JsonReaderException

Hello,

When getting a cookie containing a complex object, an exception is thrown :
Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: Q. Path '', line 0, position 0. at Newtonsoft.Json.JsonTextReader.ParseValue() at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings) at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings) at CookieManager.DefaultCookieManager.GetExisting[T](String key) at SecretariatMedical.Controllers.LoginController.Index(LoginViewModel model, Nullable1 OuvreNouvelleConnexion) in C:\Users\SylvainB\Desktop\aspnetcore\Projet Clinique Charles\SecretariatMedical\SecretariatMedical\Controllers\LoginController.cs:line 164
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.InvokeCore(HttpContext context)
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)`

Here is the line where the problem happens :

Dictionary<string, Dictionary<string, ClientSiteIdentifier>> alreadyExistingList = _cookieManager.Get<Dictionary<string, Dictionary<string, ClientSiteIdentifier>>>("ListeConnexionsMultiSiteParUtilisateur");

Here is the line where I store the object in the cookie :

_cookieManager.Set("ListeConnexionsMultiSiteParUtilisateur", alreadyExistingList, new CookieOptions() { HttpOnly = true, Expires = DateTime.Now.AddDays(30) });

Do you have any idea what could cause this problem ?

Thanks for your help !

Sylvain

IFeatureCollection has been disposed. Object name: 'Collection'.

Hi,
I'm using this package in a net6 code and was getting the error "IFeatureCollection has been disposed. Object name: 'Collection'."

After some investigation, I found that the issue was occurring in the HttpCookie class. The problem was that the _httpContext private field was storing the _httpAccessor.HttpContext is in the construction of the class, but the HttpContext is only valid during the request lifetime, so we can't cache it in a private field.

To fix that, all that I did was change the _httpContext to be an arrow function with will always get the HttpContext from _httpAccessor.HttpContext (private HttpContext _httpContext => _httpAccessor.HttpContext)

` public class HttpCookie : ICookie
{
private readonly IDataProtector _dataProtector;
private static readonly string Purpose = "CookieManager.Token.v1";
private readonly CookieManagerOptions _cookieManagerOptions;
private readonly ChunkingHttpCookie _chunkingHttpCookie;
private IHttpContextAccessor _httpAccessor;

	/// <summary>
	/// An HttpContext is the context of a single request. It provides access to the request, response properties etc of that single request. You can't cache it, it becomes invalid once that request ends.
	/// See more: https://stackoverflow.com/questions/59963383/session-setstring-method-throws-exception-ifeaturecollection-has-been-disposed
	/// </summary>
	private HttpContext _httpContext => _httpAccessor.HttpContext;



	/// <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,
		IDataProtectionProvider dataProtectionProvider,
		IOptions<CookieManagerOptions> optionAccessor)
	{
		_httpAccessor = httpAccessor;
		//_httpContext = httpAccessor.HttpContext; //NOT NEEDED ANYMORE
		_dataProtector = dataProtectionProvider.CreateProtector(Purpose);
		_cookieManagerOptions = optionAccessor.Value;
		_chunkingHttpCookie = new ChunkingHttpCookie(optionAccessor);
	}`

Now it is working very well.

It would be good to add this fix to this package.

Thanks

Can't use with netcore 2

Suggest changing the csproj targetframework from netcoreapp1.0 to netstandard1.6. I can do a PR if you want but it is a pretty minor change.

cookie result is empty

I've tried operations one-to-one,

_cookie.Set ("Key", "value here", 10);
string keystr = _cookie.Get ("Key"); // result empty is coming.

with the order of transactions,
nuget package download,
Including Icookiemanager and Icookie from the project
then middleware
services.addcookiemanag is ();
I added the code.
but the value is empty.

_cookie.Set failed

The first time I run the project, it doesn't weed out the cookies in the morning.

I am using version 2.0.0.

15 minutes after running the project a cookie occurs and the evening until the end of work is not a problem. Can you help with what the problem can be?

"LanguageIdKey" Unable to create

image

Cookie Expires always 6 hours and 5 minutes

Hi

I cannot seem to get the cookie expires to accept my value, I have tried all three ways:

startup DefaultExpireTimeInDays
controller Set with new CookieOptions()
controller Set with minutes

But it always defaults to 6 hours and 5 minutes no matter what, is this a bug or am I missing something?
image

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.