Cookie Authentication In ASP.net Core 2.0

In a previous post, I talked about getting Cookie Authentication up and running in ASP.net Core 1.X. In ASP.net Core 2.0, there has been a couple of changes to the API that are pretty easy to trip up on. Most of the changes are just a simple naming difference, but it can be pretty infuriating following a tutorial where one word trips you up! So let’s go!

Firstly, remember that this tutorial is for adding authentication to your app when you don’t want to use the out of the box “identity” services provided by ASP.net Core. It’s a very simple way to provide authentication cookies based on any logic you want, with any backing database you want.

Setup

If you are creating a new project, ensure that the “Authentication Type” when creating the project in Visual Studio is set to No Authentication. The other authentication types you can pick revolve around the inbuilt identity service, but since we are looking to do something more custom we don’t want this.

With your project up and going. In your nuget package manager, install the following package :

In the configure method of your startup.cs. Add the following line. Note that it should always come above your call to “UseMVC”, and likely above any other middleware calls that will return a result. Middleware runs in order, so you obviously want authentication to kick in before your MVC pipeline does!

In the ConfigureServices method of your startup.cs, you need to add the Cookie Authentication services with their configuration. It should look pretty similar to the following :

Where the Login Path is the URL to your login page. Remember this page should be excluded from authorization checks!

Disabling Automatic Challenge

Microsoft has decided that any time you access an endpoint that should be authorized, you should be redirected to the login page regardless. In ASP.net Core 1.X, this was not the case. You could set a flag called “AutomaticChallenge” to false. If you do not wish to always redirect the user (e.g. You would prefer to simply return a 401 response code – a Web API using shared Cookie Authentication is a good example where this would be relevant), you can override the redirect logic like so :

This overrides the redirect logic and instead returns a simple 401. There are other events you may wish to override at the same time (For example the UnAuthorized redirect etc).

Registering A User

In exactly the same manner as Cookie Authentication in ASP.net Core 1.X, registering a user will be entirely on you and will live outside any authentication code provided out of the box by Microsoft.

Logging In A User

For logging in a user, let’s create a quick model.

Now let’s create a controller called “Account” and create a POST method that accepts our login.

If you’ve followed our previous tutorial on Cookie Authentication in ASP.net Core 1.X, then this should look pretty familiar. And that’s because it’s the exact same code with one notable exception. This line here :

In ASP.net Core 1.X is actually

So that’s the only difference here.

Authorizing Controllers

This stays the same in ASP.net Core 2.0. You can simple add the “Authorize” attribute onto any controller or action.

Logging Our A User

Logging out a user stays fairly simple with one small change. The line to sign a user out inside an action is now

Previously in ASP.net Core 1.X it was :

7 comments

  1. Does the “Viewing The Logged In User” from the 1.0 tutorial also work the same here? I am trying but not getting anything in loggedInUser

  2. I tried this on my Ang4 + ASP.NET Core app, but I get this error: “InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found.”

    1. Just tried this from scratch and right you are. It seems that in .NET Core 2, it’s very sensitive to the AuthenticationScheme names. So try this, change your services line to something like this :

      services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
      .AddCookie(options =>
      {
      options.LoginPath = "/Account/Login/";
      });

      Most notable is the call to CookieAuthenticationDefaults.AuthenticationScheme which is just a constant for the CookieAuthentication Scheme. Then the Authorize call seems to work. You will also need to change all calls to SignIn/Signout that explicitly specify a scheme to use either this new constant, or none at all seems to work also.

  3. Hello,

    Thanks for the tutorial, it helped me a lot.
    I just wanted to know, if the user doesn’t sign out (so SignOutAsync doesn’t get called), does the cookie expire?

    Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *