4

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.

1
  • Add a question and more context why you want to do this. Commented Jul 21, 2016 at 7:06

2 Answers 2

10

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

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

2 Comments

await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", principal); var p = User.Identity.Name; After authentification user name is null
what exactly does the nuget do? i did notice the extension doesn't seem to be a part of it. it compiles well without the nuget however it doesn't run without the nuget
-1

The FormsAuthentication.SetAuthCookie method is part of the System.Web.Security namespace in ASP.NET, which is included in the .NET Framework. Therefore, you can use the FormsAuthentication.SetAuthCookie method in your ASP.NET application without any additional packages or libraries.

Have you tried this : FormsAuthentication.SetAuthCookie doesn't [Authorize] in MVC 5

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.