8

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

8
  • 7
    APIs are stateless. They don't have sessions. Commented Feb 25, 2019 at 14:22
  • Thanksfor your response @Chris Pratt .Is there any other possible to maintain the session Commented Feb 25, 2019 at 14:24
  • 2
    No. There's no session to maintain. Each request is unique, and you must pass in all data necessary to service the request along with the request (via the request body and/or request headers). It's not clear what you're ultimately trying to achieve, so it's impossible to help you further than that. Commented Feb 25, 2019 at 14:26
  • @ChrisPratt how can we store small info between user of api? if no session exist in web api? Commented Oct 29, 2019 at 7:44
  • That's not how APIs work. The client is responsible for transmitting back any and all information the server needs. The server simply sends the info the client needs via the response. This then just becomes part of your documented API, i.e. the server returns X in the response body, you, as the client, need to send X back as part of your request. Commented Oct 29, 2019 at 12:37

6 Answers 6

8

Actually .net core can access session easily. Session mechanism is a basic feature in aspnet (.netcore as well) https://learn.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.

Sign up to request clarification or add additional context in comments.

1 Comment

Injecting ISession ? Can you please elaborate
3

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://learn.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.

1 Comment

does this also work for an API base project
2

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.

Comments

1

In ASP.NET Core 5 - WebAPI,

  1. Create a UserLoginSessionMiddleWare class.
    public class UserLoginSessionHandlerMiddleware
    {
        private readonly RequestDelegate _next;
        public UserLoginSessionHandlerMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public async Task Invoke(HttpContext httpContext, IJwtAuthentication jwtAuthentication)
        {
            var token = httpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
            var userType = jwtAuthentication.ValidateToken(token);
            if (userType != null)
            {
                httpContext.Items["CurrentUser"] = userType;
            }
            await _next(httpContext);
        }
    }
  1. Inside Invoke() method, access Microsoft.AspNetCore.Http.HttpContext object as parameter.
  2. Create and assign the myObject that needed to store in session like, httpContext.Items["SessionObject"] = myObject;
  3. Add UserLoginSessionHandlerMiddleware to request pipeline in Startup.cs -> Configure() method. app.UseMiddleware<UserLoginSessionHandlerMiddleware>();
  4. Access the httpContext.Items["SessionObject"] from your ApiController class

Comments

-1

First install nuget package - Microsoft.AspNetCore.Session

In Startup.cs file

public void ConfigureServices(IServiceCollection services)
{
    .....
    services.AddSession(options => {
        options.IdleTimeout = TimeSpan.FromMinutes(20);//You can set Time  
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
        });
    .....
}

public void Configure(IApplicationBuilder app)
{
    ....
    app.UseSession();
    ....
}

In HomeController file

using Microsoft.AspNetCore.Http;

public class HomeController : Controller
{    
    public ActionResult Index()
    {   
      HttpContext.Session.SetString("key", "value"); // Set Session  
      var x = HttpContext.Session.GetString("key"); // Get Value of Session
    }    
}

You can also set integer value in session, use SetInt32 method and get from GetInt32 method. Hope it helps you..

1 Comment

The question pertains to Web API Controllers and NOT MVC Controllers.
-1

I hope this is the solution you are looking for

in startup.cs

in Configure method add the below code

app.UseSession();

in ConfigureServices method add the below code

  services.AddDistributedMemoryCache();
    services.AddSession(x=> 
    {
       x.Cookie.Name = "Cookie name";
       x.IdleTimeout = TimeSpan.FromMinutes(5); // idle time for the session                
    });

I creating the session in the class file example : UserLogin.cs

    private ISession session => httpContext.Session;
        public UserLogin(HttpContext httpContext)
        {
            this.httpContext = httpContext;
        }
   private void SetSession(ClassInstance ObjOutput)
        {

            session.SetString("SessionID", ObjOutput.strSession.ToString()); 
        }

in the above code i have injected the HttpContext to class and strSession is the GUID which i will get it from SP,

To validate the session in the api, create the Action filter, In that filter you can get the session in the from context of the OnActionExecuting(ActionExecutingContext context) method

context.HttpContext.Request.Headers["Session"]; this line will get the session from header
context.HttpContext.Session.GetString("SessionID"); this line will get the current session 

if it both matches it is okay if not

you can use the below code to tell session expired

string strExceptionOutput = JsonConvert.SerializeObject(new response()
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    message = "Session Expired"
                });
                response.ContentType = "application/json";
                context.Result = new BadRequestObjectResult(strExceptionOutput);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.