Coder Social home page Coder Social logo

aspnet / session Goto Github PK

View Code? Open in Web Editor NEW
125.0 50.0 67.0 521 KB

[Archived] Session state middleware for ASP.NET Core. Project moved to https://github.com/aspnet/AspNetCore

License: Apache License 2.0

Shell 8.10% C# 85.63% Batchfile 0.45% PowerShell 5.82%
aspnet-product

session's Introduction

Session [Archived]

This GitHub project has been archived. Ongoing development on this project can be found in https://github.com/aspnet/AspNetCore.

Contains libraries for session state middleware for ASP.NET Core.

For ASP.NET 4.x session state, please go to https://github.com/aspnet/AspNetSessionState.

This project is part of ASP.NET Core. You can find samples, documentation and getting started instructions for ASP.NET Core at the AspNetCore repo.

session's People

Contributors

ajaybhargavb avatar aspnetci avatar brennanconroy avatar chengtian avatar davidfowl avatar dougbu avatar eilon avatar haok avatar hishamco avatar javiercn avatar jkotalik avatar juntaoluo avatar justinvp avatar kichalla avatar mikeharder avatar natemcmaster avatar ntaylormullen avatar pakrym avatar pranavkm avatar ryanbrandenburg avatar tratcher avatar troydai 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  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  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

session's Issues

Add an option when configuring service to always create cookie

Normally when I'm making sites in other frameworks, I enjoy the fact that they will default to creating a session & cookie for every client.

It would appear as though in this library, the cookie is only set when some state is assigned to it.

Would be nice to have something like alwaysCreate or some better option name to SessionOptions.

Possible session state race condition

Isn't there a possible race condition in session middleware?

Example if I would send two simultaneous ajax requests both modifying session first would set key called "key1" and second would set key called "key2".
Because there are no locks there is big possibility that only one of the keys would be set. If both would load the session and then last request to call CommitAsync would overwrite other request's modified session state.

This was handled by previous Asp.Net by only allowing one request with writable session for one session id at a time.
That solution wasn't very good performance.

Better solution would be have some sort of session update scope that would lock then load current session state for you to modify and after scope ends it would commit changes and unlock.

If that is too big of a change you should atleast fix current implementation so that setting single key only overwrites that key and not the whole session state.

Installing the Session package cause errors in the Application

After Installing the package on a new project, I get the following errors

error file
CS0012 The type 'AuthenticationProperties' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.AspNet.Http.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. tx.DNX 4.5.1 Controllers\AccountController.cs 147
CS0012 The type 'HttpContext' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.AspNet.Http.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. tx.DNX 4.5.1 Controllers\AccountController.cs 460
CS0266 Cannot implicitly convert type 'System.Collections.Generic.List<Microsoft.AspNet.Http.Authentication.AuthenticationDescription>' to 'System.Collections.Generic.IList<Microsoft.AspNet.Http.Authentication.AuthenticationDescription>'. An explicit conversion exists (are you missing a cast?) tx.DNX 4.5.1 Controllers\ManageController.cs 286

here is my project.json file

{
  "webroot": "wwwroot",
  "userSecretsId": "xxx",
  "version": "1.0.0-*",

  "dependencies": {
    "EntityFramework.Commands": "7.0.0-beta8",
    "EntityFramework.SqlServer": "7.0.0-beta8",
    "Microsoft.AspNet.Authentication.Cookies": "1.0.0-beta8",
    "Microsoft.AspNet.Authentication.Facebook": "1.0.0-beta8",
    "Microsoft.AspNet.Authentication.Google": "1.0.0-beta8",
    "Microsoft.AspNet.Authentication.MicrosoftAccount": "1.0.0-beta8",
    "Microsoft.AspNet.Authentication.Twitter": "1.0.0-beta8",
    "Microsoft.AspNet.Diagnostics": "1.0.0-beta8",
    "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-beta8",
    "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-beta8",
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-beta8",
    "Microsoft.AspNet.Mvc": "6.0.0-beta8",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta8",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-beta8",
    "Microsoft.AspNet.Session": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-beta8",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta8",
    "Microsoft.Framework.Configuration.Abstractions": "1.0.0-beta8",
    "Microsoft.Framework.Configuration.Json": "1.0.0-beta8",
    "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta8",
    "Microsoft.Framework.Logging": "1.0.0-beta8",
    "Microsoft.Framework.Logging.Console": "1.0.0-beta8",
    "Microsoft.Framework.Logging.Debug": "1.0.0-beta8",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta8"
  },

  "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel",
    "ef": "EntityFramework.Commands"
  },

  "frameworks": {
    "dnx451": {}
  },

}

Apply IDataProtection to the session cookie value

The session cookie values are opaque GUIDs used to look up entries in the IDistributedCache. However, we don't have any verification saying we actually issued said cookie. Use IDataProtection to sign and validate the value. Otherwise ignore it and create a new session.

access to session key/id via ISession

couldn't find a way to retrieve session id the first time session has been established and before it gets written to cookie. there might be a need to track session key/id for custom metrics purpose similar to how the session id is currently logged to logger.

Session Cookie Expiration

It doesn't appear possible to set cookie expiration for a session. So, as you know, when the browser is restarted, the session is gone. This prevents the possibility of implementing "remember me"-like functionality. Are there plans to include session cookie expiration into the session package, or perhaps I am missing something as it is?

IHttpContextAccessor is must for random class?

As far as i know if we want to implement Session in any normal class which is not a controller we can access the HttpContext by injecting IHttpContextAccessor.

So like:

private readonly IHttpContextAccessor _httpContextAccessor;

public SessionUtility(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}

I would like to know if there is any default wrapper is made for this or it is final implementation?

Reason for this is to update it in my Post which is here: https://neelbhatt40.wordpress.com/2015/09/07/implement-sessions-in-asp-net-5vnext-and-mvc-6/

Memory-backed session doesn't seem to be working correctly in RC1

I'm having difficulty getting session variables to persist across requests when using Microsoft.Extensions.Caching.Memory. Steps to reproduce are:

  1. Create a new project using the ASP.NET 5 Web Application template in VS 2015 Update1, with no authentication.
  2. Add the following to the end of the project.json file:
"Microsoft.AspNet.Http": "1.0.0-rc1-final",
"Microsoft.AspNet.Session": "1.0.0-rc1-final",
"Microsoft.Extensions.Caching.Memory": "1.0.0-rc1-final"
  1. Amend the StartUp.ConfigureServices method as follows:
public void ConfigureServices(IServiceCollection services)
{
    services.AddCaching().AddSession().AddMvc();
}
  1. Add app.UseSession(); to the beginning of the Configure method.
  2. Add using Microsoft.AspNet.Http; to the HomeController class and amend the Index and About methods:
public IActionResult Index()
{
    HttpContext.Session.SetString("Message", "Hello World");
    return View();
}

public IActionResult About()
{
    ViewData["Message"] = HttpContext.Session.GetString("Message");
    return View();
}

When I add a breakpoint to the Index method, I can see that the Session _store has a Count = 1, but the backing store (_memCache) has 0 entries. When the About method is invoked afterwards, the session collection has 0 entries.

Am I overlooking something?

Session.Cancel()

Can we have a way to cancel the current session, something looks like Session.Abandon(). This may related to the issue #20 because it should fire a onEnd event

Getting new session id for every web request

Session is not maintained between web requests.

In Startup->ConfigureServices()
services.AddMvc();
services.AddCaching();
services.AddSession();

In Startup->Configure()
app.UseSession();
app.UseMVC(...)

I see the services.AddSession() has:
ServiceCollectionExtensions.AddTransient<ISessionStore, DistributedSessionStore>(services);

Should this be a scoped service?

SQL Session with simultaneous In-Memory Cache?

Is it possible to run SQL backed Session while simultaneously using in-memory implementation for general caching?

If so, can you point me to some samples of how to properly configure the services to accomplish that scenario?

My use case is needing out-of-proc sessions (due to load balancing bouncing users around servers) while at the same time wanting the performance of in-proc caching for controller output fragments, etc.

Thanks!

Getting the ISession injected

Hello,

Is it possible to imagine that ISession can be directly registered in the DI container ? Perhaps throught a factory that use the ISessionFeature ?
This is only to lighten syntax while using session. The HttpContext is not really testable and I think that injecting an ISession into my controller would be much easier than injecting ISessionFeature to finally get the ISession.

Thanks

must we swallow an error if session is not configured?

I'm using an extension method on controller to set alerts using TempData which in turn depends on session, code for the method is as follows:

private static void AddAlert(
        this Controller controller,
        string alertStyle,
        string message,
        bool dismissable)
    {
        try
        {
            if(controller.Context.Session != null)
            {    
                var alerts = controller.TempData.ContainsKey(Alert.TempDataKey)
                ? (List<Alert>)controller.TempData[Alert.TempDataKey]
                : new List<Alert>();

                alerts.Add(new Alert
                {
                    AlertStyle = alertStyle,
                    Message = message,
                    Dismissable = dismissable
                });

                controller.TempData[Alert.TempDataKey] = alerts;
            }


        }
        catch(InvalidOperationException)
        {
            // happens if session is not configured
            // TempData depends on session
        }

    }

I don't like it that it I'm having to catch System.InvalidOperationException even though I'm checking if session is null. If I remove the check for null the error is not stopped by the try catch so it completely breaks the app if session is not configured. Adding the null check somehow made it possible to catch the exception.
Of course I can fix it by enabling session, but my code is in a library that I expect others to use and I don't want to force them to enable session if they don't want to. If they don't enable session I want the alerts feature to fail silently, it will be documented that to use it session must be enabled. But in that scenario I'm forced to keep swallowing the exception which seems undesirable.

Is there any way to detect if session is available without raising an exception?

How to check is session is available/configured

With NLog users can log session values (e.g. to file).

In ASP.NET4 this works well, but with this library we have the following issues:

How do we check (without writing a log message) if the session is available/configured, so that we can prevent these issues?

Related #99, https://github.com/NLog/NLog.Extensions.Logging/issues/28

Session Events

Is there any plans to implement Session events (onStart, onEnd) which we have seen in global.asax before

Getting session id

As seen at #49 reading session ids aren't supported anymore?

Are there any plans to still get the session-id? Because this is a big breaking change - and in my opinion unneeded.

We need it for logging purposes. Maybe session-ids aren't perfect, but AFAIK there are still existing (but not readable).

Dealing with unreliable storage

One of the larger complaints with Asp.Net 4 Session is that when the session provider goes down it takes down the entire site, when session may not be a critical component of the site.

We have not hardened the new implementation to handle this scenario. There are several TODOs in the code (https://github.com/aspnet/Session/blob/dev/src/Microsoft.AspNetCore.Session/DistributedSession.cs#L105) around suppressing session load failures. We even had an ISession.IsAvailable property to indicate this, but I think it was removed when nobody used it.

Asynchronous version of Session.Get & Session.Set

As we know that there many session management techniques are present such as InMemory, Distributed or even Database, some of them may takes long time to get or set the values in the store, indeed we need to support async as first class

The dependency Microsoft.AspNet.Session >= 1.0.0-rc1-final could not be resolved

My Project.json

"dependencies": {
"EntityFramework.Commands": "7.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
"Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
"Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final",
"Microsoft.AspNet.Session": "1.0.0-rc1-final",
"Microsoft.AspNet.Http": "1.0.0-rc1-final",
"Microsoft.AspNet.Http.Extensions": "1.0.0-rc1-final",
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
"Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
"Microsoft.Extensions.DependencyInjection": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final"
},

Install asp.net rc1 and when I download the asp.net session shows me the error: The dependency Microsoft.AspNet.Session> = 1.0.0-rc1-end Could not be resolved, not how to fix it.

thank you

Add messages to Resource file

It will be nice to move all string messages to a resource file for clarity also it be easy for localization purpose. Let me know if sound is good to create a PR for that
/cc @Tratcher

Add Secure cookie flag option to session cookie

The session cookie needs the ability to have the 'Secure' flag set.

This depends on aspnet/HttpAbstractions#612.

Note we considered doing this in the past (#28), but we considered the Microsoft.AspNetCore.CookiePolicy middleware to be adequate. That's no longer the case because we want to apply token binding data protection based on if the cookie will be marked as Secure.

Improve the documentation

It will be nice if we provide a rich documentation for public APIs, because what i have seen that one or two classes have a proper documentation.

/cc @Tratcher

Secure Coding Compliance

Hello,

we need to be compliant with various secure coding standards (and non-disclosure secure coding requirements) as for example the OWASP ASVS3.0.

I miss convenient methods to acheive
a) session id regeneration
b) access to the session id
c) "secure" cookie attribute.

If i simply missed them please point me there. Otherwise i would be glad to know the plans on these topics.

Possible to use Token instead of Cookie?

Is there a way to use Token passed in custom header instead of cookie to pass session ID?
As per docs only cookie can be used to pass session ID around.

We have microservice architecture with centralized session storage. A token based approach seems to be more suitable instead of keeping a domain level cookie to pass around.

Session middleware for session affinity

As far as I remember correctly, in System.Web world, session locks the requests and only allows one request to go through at a time per session (I could be wrong). Is this also the behavior we get with this session middleware?

I want to provide session affinity for my web applications but I am not sure if the session middleware if the right choice to provide that. If it has the lock behavior I mentioned about, it wouldn't fit well.

Add sessionid to isession

The sessionid is already used in some parts like logging and creating sessions. With that in mind, it's strange that we can't read the sessionid when we use isession - it seems that sessionid is a important part of the whole session (otherwise why log it) .

Also in the previous versions of asp.Net, the sessionid was readable.

So please think of including sessionid in isession.

(limited Internet device now - mobile - so ignore the full lowercase names)

Lazy initialisation of session

Is there a way to do "lazy" initialisation of the session - ie. start the session only when it's actually being used? At the moment, using the session middleware initialises the session on every single page regardless of whether it's actually used on that page, which prevents caching of every single response at a reverse proxy (as responses with cookies are not cacheable at any intermediary server). On my site, only certain pages uses the session, whereas others are fine without it (and I want to cache those pages in Nginx).

Registering caching together with session

Adding session without adding caching always throws on first temp data access:

public void Configure(IApplicationBuilder app)
{
    app.UseSession();
    // Other code
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddSession();
    // Other code
}

maybe AddSession could register caching by default if it's required anyways?
Because dependency injection says very little about what is wrong with me codez :octocat:

Session issue in Chrome

I notice from couple months ago a strange behavior while I run the sample in Chrome browser, the visits session increment by two instead of one!! I upgrade the Chrome today, but the same behavior occurs, i'm not sure what causes this bug

Session write concurrency

Is there any concern about how this implementation doesn't appear to allow for concurrent write access to session data? If request A starts and reads from session, then request B starts, reads, and writes to session, and then request A writes to session and finishes, then the data data written by B is lost -- even if it's a different session variable that request B used.

While I love the fact that requests are not locked to maintain session integrity, there must be a way to maintain for concurrent requests to safely update the session. Could there be some change tracking added?

Make changes as per api review

Tracking item for making changes as per API review.

Additional notes:

  • To limit number of abstractions like ISession, ISessionFactory, ISessionFeature and ISessionCollection, one of the ideas is to remove Session property from HttpContext. Since Session is an optional feature any ways, we could provide an extension method on HttpContext like GetSessionAsync, which when called loads the session in an asynchronous way.
    The setting and getting of values is synchronous.
// In an Mvc action (pseudo code):
var session = await Context.GetSessionAsync();
session.SetInt32("key1", 100);
  • Currently session data is loaded on-demand, i.e the first time a user tries to get/set a value in it. Users get/set the value using synchronous api, which forces us to do a blocking call when loading the session.
    Can we avoid this blocking call and make users use async api as the example in point 1 above? I think any change here would have an impact on backward compatibility too.
    Also the TempData feature in MVC uses Session internally and so if we want to make async changes, it would have to be reflected in TempData too.
  • Let Session and TempData be synchronous as they are today for simplicity sake, but also provide asynchronous apis for users who are looking for more performance.

@Eilon @Tratcher @muratg

Session is not working on IIS with CORS

I am using sessions to manage application state in ASP.NET CORE and it's configured as below.

 services.AddSession(options =>
            {
                options.CookieName = ".my.Session";
                options.IdleTimeout = TimeSpan.FromSeconds(20);
            });

It's working on localhost but on remote IIS 8 it's not creating cookies so not able to get the values. I also have enabled CORS and don't know what exactly caused this problem. In log it's not showing error either. It's creating session getting stored id but no cookie at client side.

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.