ASP.NET Core 2: Custom Authentication Part 2

Browser-Cookies.jpgIn Part 1 we asked ASP.NET Core to use Cookie based authentication and to include the authentication engine into the request pipeline. In this next simple example, we’ll log the user in and verify they are logged in. ASP.NET Core has a built-in user system, however in these posts I’m assuming you can’t use that and have to use an external user database or web service.

To keep this as narrowly focused as possible, I am skipping the User Manager features like looking up the user in a database and comparing password hashes. If you need a good UserManager.cs file for ASP.NET Core outside of the built-in one, here’s a good one.

In the HomeController.cs add this function. It’ll handle a complete Login:

[AllowAnonymous]
public async Task<IActionResult> SignIn()
{
 
    //Create a plain C# Class
    //In real-life, get this from a database after verifying the username and password
    MyUser user = new MyUser()
    {
        Id = 1,
        Name = "Fred Fish"
    };
 
    //Add the ID of the user and the name to a collection of Claims
    List<Claim> claims = new List<Claim>
    {
        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
        new Claim(ClaimTypes.Name, user.Name)
    };
 
    //Create the principal user from the claims
    ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
    ClaimsPrincipal principal = new ClaimsPrincipal(identity);
    AuthenticationProperties authenticationProperties = new AuthenticationProperties() {IsPersistent = false};
 
    //Ask MVC to create the auth cookie and store it
    await this.HttpContext
            .SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, 
             principal, authenticationProperties);
 
 
    //DONE!
    return this.RedirectToAction("Index");
}

Let’s break this down now:

We first need a User class, this can be a plain old C# object. There is no magic here.

public class MyUser
{
    public int Id { getset; }
    public string Name { getset; }
}

Next we need to add information about the user we just made to a collection of Claims. Claims can contain groups or roles or names and ids. Think of it as the bucket of certified security information about a user.

List<Claim> claims = new List<Claim>
{
    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
    new Claim(ClaimTypes.Name, user.Name)
};

We now wrap up all the claims and info about the user into a Principal:

ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
AuthenticationProperties authenticationProperties = new AuthenticationProperties() { IsPersistent = false };
ClaimsPrincipal principal = new ClaimsPrincipal(identity);

And finally, take the Principal and ask the HttpContext to store it in a cookie:

await this.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, authenticationProperties);

We are now logged in. To check, in the post-login View, have a look at the User

@if (this.User.Identity.IsAuthenticated)
{
    <b>Authenticated!</b>
} 

Done!

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s