ASP.NET Core 2: Custom Authentication Part 1

ASP.NET Core 2 comes with easy to use out-of-the-box authentication. In Visual Studio 2017 you can create fully functioning projects via the File | New menu.

These next few tutorials will focus on doing a custom implementation. Perhaps your organization wishes to authenticate against a customer database, or even a web service. I’ll show you how to implement that all using the beautiful ASP.NET Core 2 authentication infrastructure.

Step 1: Create a new blank project, no authentication

For this tutorial we’ll use “.NET Framework” as we’ll be hosting in IIS

custom auth.png

Step 2: Add the NuGet package Microsoft.AspNetCore.Authentication.Cookies

Step 3: In Startup.cs add Cookie customization for the authentication cookie:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
            {
                options.ExpireTimeSpan = TimeSpan.FromDays(7);
                options.LoginPath = "/Account/CustomLogin";
                options.Cookie.Name = "MyAuthCookieName";
            }
        );
 
    services.AddMvc();
}

Step 4: In Startup.cs ‘s Configure method add UseAuthentication()

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }
 
    app.UseAuthentication();  //IMPORTANT
    app.UseStaticFiles();

 

 

In the cookie customization, you can change many features like the login page from the default “/Account/Login” and the name of the Cookie. The defaults are sensible however.

In Part 2 we’ll add a UserManager class which will handle authentication.

This post is possible based on the excellent work at this site.

Advertisements

One thought on “ASP.NET Core 2: Custom Authentication Part 1

  1. Pingback: ASP.NET Core 2: Custom Authentication Part 2 | Xamarin and Visual Studio for Beginners

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