Home > database >  Access session variables across all controllers in .net core 5.0
Access session variables across all controllers in .net core 5.0

Time:02-08

I have been researching this for a minute but nothing seems to work. I want to be able to set multiple session variables at different points in time and access them across all controllers.

I have tried the below:

I created a base controller and set a public string of the variable I want to access.

 public class BaseController : Controller
    {
       public string UserToken
        {
            get
            {
                string token = HttpContext.Session.GetString("SessionUserToken");
                return token == null ? null : token.ToString();
            }
            set
            {
                HttpContext.Session.SetString("SessionUserToken", value);
            }
        }
    }

then I inherited from the base controller into my home controller

 public class HomeController : BaseController
 { 
    public async Task<IActionResult> Index()
    {
            string userToken = HttpContext.Session.GetString("SessionUserToken"); ;
            if (userToken == null)
              //do something
            else 
             //do something else
    }
       
 }

And in another controller as well

 public class ProfileController: BaseController
 { 
    public async Task<IActionResult> Login(LoginModel login)
    { 
       Login account = await _Repository.Login(login);
          if(account.succeeded)
           {
               UserToken = account.data;
           }else{
              redirectToAction("Index", "Home");
           }
           
    }
       
 }

Does anyone know how I can accomplish this?

CodePudding user response:

Looks like your re-creating the authentication system in ASP.NET

I would very much suggest that you consider using the Cookie Authentication system that's already build in. This does NOT require you to use ASP.NET Identity.

See https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-6.0

In your startup file you would have to set

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
        options.SlidingExpiration = true;
        options.AccessDeniedPath = "/Forbidden/";
    });

Then in your ProfileController you can run the below code to set the authentication cookie.

var claimsIdentity = new ClaimsIdentity(new List<Claim>
{
    new Claim("SessionUserToken", account.data)
}, CookieAuthenticationDefaults.AuthenticationScheme);

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme, 
    new ClaimsPrincipal(claimsIdentity), 
    new AuthenticationProperties());

Then you can validate access either using the classic attributes like [RequiresAuthentication] or you can check User.IsAuthenticated and when you need the SessionUserToken you can access User.FindFirstValue("SessionUserToken")

  •  Tags:  
  • Related