Developing token authentication using ASP.NET Core

Developing token authentication using ASP.NET Core

(Credits :Virtual street art Golinelli )

Introduction

The following article shows how to developing token authentication using ASP.NET Core.

I have already written about ASP.NET Core here:

Token based authentication overview

Nowadays, Token based authentication is very common on the web and any major API or web applications use tokens.

Token authentication is stateless, secure and designed to be scalable. In fact, it is quickly becoming a de facto standard for modern single-page applications and mobile apps.

Developing token authentication using ASP.NET Core

The problems with server based authentication

Authentication is the process by which an application confirms user identity. Applications have traditionally persisted identity through session cookies, relying on session IDs stored server-side. A few major problems caused by this technique:

  • Scalability: if sessions are stored in memory, this provides problems with scalability;
  • CORS: as we want to expand our application to let our data be used across multiple mobile devices, we have to worry about cross-origin resource sharing (CORS);
  • CSRF: we will also have protection against cross-site request forgery(CSRF);
  • Sessions: Every time a user is authenticated, the server will need to create a record on our server;

How token based authentication works

Token based authentication is stateless. It don’t store any information about our user on the server or in a session.

Here’s the common steps of the token based authentication:

  1. user requests access by using username / password;
  2. application provides a signed token to the client;
  3. client stores that token and sends it along with every request;
  4. server verifies token and responds with data;

Every single request will require the token. The token should be sent in the HTTP header to keep the idea of stateless HTTP requests.

Implementing Token based authentication using ASP.Net Core

This example shows how to developing token authentication using ASP.NET Core, the following  UML schema shows the architecture of project:

Developing token authentication using ASP.NET Core

Setup the project

First of all, is necessary create new ASP.NET Core project. I suggest to use ASP.NET Yeoman Generator to generate project using Web application template and Visual Studio Code to edit the code.

Once the project is successfully created, add the following configurations to your appsettings.json:

The TokenAuthentication section configures some common information about token generation, for example the SectionKey used by token.

Tokens transmission / validation

There are two ways to transmit the authorization tokens:

  1. using  HTTP Authorization headers (aka  Bearer authentication);
  2. using browser cookies to save the authentication token;

Bearer token validation

The  Microsoft.AspNetCore.Authentication.JwtBearer package enables you to protect routes by using a JWT Token.

To enable Bearer token authentication, import the following Nuget package Microsoft.AspNetCore.Authentication.JwtBearer  in the project.json:

To initialize the Bearer authentication you need to split your Startup.cs file and use another partial class, for example Startup.Auth.cs:

The Startup.Auth.cs file initialize the Bearer Authentication using  configurations defined in the appsettings.json file. The tokenValidationParamaters object will be used also by Cookie validation.

Cookies validation

Cookies validation enables the Token transport over browser cookies, to enable the Cookie token authentication you need to add the following package inside the project.json:

"Microsoft.AspNetCore.Authentication.Cookies": "1.0.0"

and  create a custom validator for the input token.

To create the new validator add the following CustomJwtDataFormat.cs file:

Unprotect method decript and validate information provided by the input token. Call the following method in the Startup.Auth.cs file, to use the Cookie authentication:

Token generation

There isn’t native support to Token generation in ASP.NET Core, but it is possible write a custom token generator middleware from scratch.

Firstly, you need to create a class which implement token options :

The middleware class will use TokenProviderOptions.cs to generate tokens:

The TokenProviderMiddleware class implement the Invoke method to generate tokens by using the TokenProviderOptions. In order to initialize the middleware, it is necessary modify the Startup.Auth.cs file and add in the ConfigureAuth method:

The tokenProviderOptions defines the options of the token generator. The IdentityResolver is the Task method which will check the identity of users. For demo purposes, the IdentityResolver is implemented by a simple method called GetIdentity.

Final steps

Now is possible call the ConfigureAuth method inside the Startup.cs file:

Getting token

You can obtain the JWT token by calling the following route /api/token/ using POST and passing the username and password data:

POST api/token
Content-Type: application/x-www-form-urlencoded
username=TEST&password=TEST123

Authorize controllers

All controllers decorated by the attribute [Authorize] are protected by the JWT authentication.
In each http call you need to pass the access_token parameter:

You need to pass the token in the header request:

Authorization:Bearer MY_TOKEN

UPDATE: The project runs on .NET Core 2.0. The demo code is available on Github.

Cheers 🙂