Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create and Access Session .net core api?

I need to create and access session in api. For example i have api called Login,Profile. When the login api is called at that time i need to create session and i need to access the session in profile api. When the session is cleared the login and profile api don't allow the user to access. How to do it.

Thank you..

like image 315
SATHEESH P Avatar asked Feb 25 '19 14:02

SATHEESH P


3 Answers

Actually .net core can access session easily. Session mechanism is a basic feature in aspnet (.netcore as well) https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2

I think you just need to add

    services.AddDistributedMemoryCache();

    services.AddSession(options =>
    {
        // Set a short timeout for easy testing.
        options.IdleTimeout = TimeSpan.FromSeconds(10);
        options.Cookie.HttpOnly = true;
    });

in ConfigureServices and:

app.UseSession();

in Configure

Then you can use it anywhere by injecting ISession where you need. As this is distributed by design you should serialize your data using something like JsonConvert.SerializeObject and deserialize them back.

This feature described here has nothing with security concepts.

like image 90
Alex Lyalka Avatar answered Oct 15 '22 17:10

Alex Lyalka


In Startup.cs you can add cookie authentication by adding this line (you can also specify options for length of session, etc).

services.AddAuthentication().AddCookie();

To create a session on sign-in, from a controller, you can call this to sign in as a user with a set of claims (basically key/value pairs that describe what you need to know about the user):

await HttpContext.SignInAsync(userId, claims);

This creates a ClaimsPrincipal that can be accessed via the User property on Controller:

User.HasClaim("someclaim", "somevalue")

Ultimately the middleware encrypts the claims and saves them to a cookie, so the authentication is still stateless from the server's perspective. Be aware though that the encryption key it uses by default is tied to the machine so you'll have to use something like azure or redis if you plan on scaling to multiple server instances.

If you want to have a full login & user management system, the easiest way to go is probably ASP.net identity which provides the APIs for handling users, policies, access groups, and some of the tricky stuff like password storage using Entity Framework. For more info on that, check out this: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-2.2&tabs=visual-studio


As a side-note, for more generic session state, this document has data about other session state options, but since you asked about logins, the best option is probably to use the authentication APIs.

like image 26
Eric Damtoft Avatar answered Oct 15 '22 15:10

Eric Damtoft


All right, there are two things you need to do. In startup.cs:

1- Add app.UseSession(); to Configure method.

2- For more controlling on cookies insert following codes into ConfigureServices method:

options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;

Like this if it solved problem.

like image 27
Alireza Abdollahnejad Avatar answered Oct 15 '22 16:10

Alireza Abdollahnejad