Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set authentification in asp net core (asp net 5)

I need the ability to authentificate my user from code in test like this

var identity = new GenericIdentity("[email protected]", "UserId");
Thread.CurrentPrincipal = new GenericPrincipal(identity, null);

Or like this

FormsAuthentication.SetAuthCookie(username, rememberMe);

But these methods not working in asp net 5.

like image 805
user3555620 Avatar asked Oct 16 '25 12:10

user3555620


1 Answers

To get this to work in ASP.NET Core, first, use NuGet to add Microsoft.AspNetCore.Authentication.Cookies

In Startup.cs, add this to the Configure method:

  app.UseCookieAuthentication(new CookieAuthenticationOptions()
  {
    AuthenticationScheme = "PutANameHere",
    LoginPath = new PathString("/Account/Login/"),
    AutomaticAuthenticate = true,
    AutomaticChallenge = true
  });

Then call this to login:

  var userClaims = new List<Claim>
    {
        new Claim(ClaimTypes.Name, userName)     
    };

  var principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims, "local"));
  HttpContext.Authentication.SignInAsync("PutANameHere", principal);

For more information on this, check this out: https://docs.asp.net/en/latest/security/authentication/cookie.html

like image 173
Rono Avatar answered Oct 19 '25 01:10

Rono