Forms Authentication in .NET Core (AKA Cookie Authentication)

In .NET Core MVC you're encourages to use .NET Identity, but you don't have to. You can manage your own user identities and you use forms authentication which is now called Cookie Authentication (which is a better name really).

You need to install the Microsoft.AspNetCore.Authentication.Cookies nuget package.

There is some configuration that needs to go in startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options => {
            options.AccessDeniedPath = "/you-are-not-allowed-page";
            options.LoginPath = "/login-page"; }
        });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication();
}

To log someone in you need to create a principal which is a representation of their identiry and can contain a collection of claims (useful bits of information about the user and what they're allowed to do). Here is an example method to create a principal for a user.

private ClaimsPrincipal CreatePrincipal(YourUserClass user)
{
    var claims = new List<Claim>
    {
        new Claim("UserId", user.Id.ToString()),
        new Claim("UserName", user.ScreenName)
    };
    var principal = new ClaimsPrincipal();
    principal.AddIdentity(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme));
    return principal;
}

Now logging someone in and out is pretty straight forward in your controller actions

public async Task<IActionResult> Login(string username, string password)
{
    var user = GetMyUser(username, password);
    // Todo: Check for no user with these credentials

    var principal = CreatePrincipal(user);

    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
    return RedirectToAction("Index", "Home");
}

public async Task<IActionResult> Logout()
{
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return RedirectToAction("Index", "Home");
}

You can access a logged in User's claims in a controller action like so:

var claimUserName = User.Claims.FirstOrDefault(c => c.Type == "UserName");

For more details of the options available to you should check out the Microsoft Docs on Cookie Authentication.

If you're looking for a way to add social login authentication using Facebook, Github, Google or Twitter in .NET Core then you should check out my library Noggin .NetCore Auth.

No Comments