Asp.Net Core - simplest possible forms authentication

Pelle picture Pelle · May 17, 2017 · Viewed 26.8k times · Source

I have this old MVC5 application that uses forms authentication in the simplest possible form. There is only one account stored in web.config, there are no roles etc.

<authentication mode="Forms">
  <forms loginUrl="~/Login/Index" timeout="30">
    <credentials passwordFormat="Clear">
      <user name="some-user" password="some-password" />
    </credentials>
  </forms>
</authentication>

The login routine just calls

FormsAuthentication.Authenticate(name, password);

And that's it. Is there something similar (in terms of simplicity) in asp.net core?

Answer

Anuraj picture Anuraj · May 17, 2017

It is not that simple :)

  1. In the Startup.cs, configure method.

    app.UseCookieAuthentication(options =>
    {
      options.AutomaticAuthenticate = true;
      options.AutomaticChallenge = true;
      options.LoginPath = "/Home/Login";
    });
    
  2. Add Authorize attribute to protect the resources you want to secure.

    [Authorize]
    public IActionResult Index()
    {
      return View();
    }
    
  3. In the Home Controller, Login Post action method, write the following method.

    var username = Configuration["username"];
    var password = Configuration["password"];
    if (authUser.Username == username && authUser.Password == password)
    {
      var identity = new ClaimsIdentity(claims, 
          CookieAuthenticationDefaults.AuthenticationScheme);
    
      HttpContext.Authentication.SignInAsync(
        CookieAuthenticationDefaults.AuthenticationScheme,
        new ClaimsPrincipal(identity));
    
      return Redirect("~/Home/Index");
    }
    else
    {
      ModelState.AddModelError("","Login failed. Please check Username and/or password");
    }
    

Here is the github repo for your reference : https://github.com/anuraj/CookieAuthMVCSample