Reputation: 429
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..
Upvotes: 8
Views: 31700
Reputation: 51
In ASP.NET Core 5 - WebAPI,
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);
}
}
httpContext.Items["SessionObject"] = myObject;
app.UseMiddleware<UserLoginSessionHandlerMiddleware>();
Upvotes: 1
Reputation: 11
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);
Upvotes: -1
Reputation: 1047
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.
Upvotes: 1
Reputation: 1405
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..
Upvotes: -1
Reputation: 1651
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.
Upvotes: 6
Reputation: 1423
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.
Upvotes: 3