Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookie without Identity Asp.net core

I'm currently working on a project that I don't use Identity.

The things is that this project should have a remember me option that allow user to automatically reconnect into the web site.

My problem is that I can't find any complete tutoriel to create a cookie without Identity.

If somebody have a good sample of code or tutoial :)

Thanks

like image 322
OrcusZ Avatar asked Jan 25 '26 05:01

OrcusZ


1 Answers

In my project, I use AngularJS for Frontend and .Net Core API for Backend. So, I don't need to configure pages for AccessDeniedPath, LoginPath and so on.

Here's what I do:

  • Configure the cookie in the startup class:

    public void Configure(IApplicationBuilder app) {
      //...
      CookieAuthenticationOptions options = new CookieAuthenticationOptions();
      options.AuthenticationScheme = "MyCookie";
      options.AutomaticAuthenticate = true;
      options.CookieName = "MyCookie";
      app.UseCookieAuthentication(options);
      //...
    }
    
  • The login is like this:

    [HttpPost, Route("Login")]
    public IActionResult LogIn([FromBody]LoginModel login) {
      //...
      var identity = new ClaimsIdentity("MyCookie");
      //add the login as the name of the user
      identity.AddClaim(new Claim(ClaimTypes.Name, login.Login));
      //add a list of roles
      foreach (Role r in someList.Roles) {
        identity.AddClaim(new Claim(ClaimTypes.Role, r.Name));
      }
      var principal = new ClaimsPrincipal(identity);
      HttpContext.Authentication.SignInAsync("MyCookie", principal).Wait();
      return Ok();
    }
    
  • The logout is like this:

    [HttpPost, Route("Logout")]
    public async Task<IActionResult> LogOut() {
      await HttpContext.Authentication.SignOutAsync("MyCookie");
      return Ok();
    }
    
  • Then you can use it like this:

    [HttpPost]
    [Authorize(Roles = "Role1,Role2,Role3")]
    public IActionResult Post() {
      //...
      string userName = this.User.Identity.Name;
      //...
    }
    

*See that the method is authorized only for "Role1, Role2 and Role3". And see how to get the user name.

like image 87
Fabricio Koch Avatar answered Jan 26 '26 17:01

Fabricio Koch