Securing ASP.NET Web API using Custom Token Based Authentication

Providing a security to the Web API’s is important so that we can restrict the users to access to it. We can provide the security in two different ways:

Basic authentication. Token based authentication.

In this blog, we will discuss how we can implement token based authentication. Below diagram shows the control flow of token based authentication.

Fig: Token based authentication for Web API’s.

How token based authentication works?

In the Token based approach, the client application first sends a request to Authentication server with a valid credentials. Authentication server send an Access token to the client as a response. This token contains enough data to identify a particular user and it has expiry time. The client application then uses the token to access the restricted resources in next requests till the token is valid. If the Access token is expired, then client application can request for new access token by using Refresh token.

Let’s see how we can implement the token based authentication for Web Api’s:

Step 1: Create a new project by following the steps below:

Open Visual studio=>File=>New=>Project=>Web=>Enter project name=>Ok=>Select Empty Template=>Check MVC and Web API checkboxes=>Click Ok.

Now the project is created successfully.

Step 2: Add following NuGet packages:

Microsoft.Owin.Host.SystemWeb

Microsoft.Owin.Security.OAuth

Microsoft.Owin.Cors

To add NuGet packages right click on References folder of your project then select Manage NuGet Packages and then add above packages.

“Microsoft Owin” is responsible for regenerating and verifying the tokens.

Step 3: Add ‘Startup.cs’ inside the ‘App_Start’ folder. Then add the following code:

[assembly: OwinStartup(typeof(WebApisTokenAuth.App_Start.Startup))]

namespace WebApisTokenAuth.App_Start

{

public class Startup

{

public void Configuration(IAppBuilder app)

{

app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

var myProvider = new AuthorizationServerProvider();

OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions

{

AllowInsecureHttp = true,

TokenEndpointPath = new PathString("/token"),

AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),

Provider = myProvider,

RefreshTokenProvider = new RefreshTokenProvider()

};

app.UseOAuthAuthorizationServer(options);

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

HttpConfiguration config = new HttpConfiguration();

WebApiConfig.Register(config);

}

}

}

Make sure to add [assembly: OwinStartup(typeof(WebApisTokenAuth.App_Start.Startup))] at the beginning as shown in the above code.

In the above sample, we can see:

AuthorizationServerProvider. RefreshTokenProvider

AuthorizationServerProvider:

It is the custom class which is inherited from the class OAuthorizationServiceProvider and overrides methods of it. Some of the methods we will discuss here:

ValidateClientAuthentication(): Called to validate the client, if context.Validated is not called the request will not proceed further.

Called to validate the client, if context.Validated is not called the request will not proceed further. GrantResourceOwnerCredentials(): This will validate the users credentials.

This will validate the users credentials. GrantRefreshToken(): It is used to change authentication ticket for refresh token requests.

RefreshTokenProvider:

This class is inherited from IAuthenticationTokenProvider interface and provides implementation for creating the refresh token and regenerate the new access token, if it is expired.

CreateAsync(): This method is responsible for creating the new access token.

This method is responsible for creating the new access token. ReceiveAsync(): This method is responsible for regenerate the new access token by using existing refresh token, if it is expired.

Step 4: Now create api controller and Authorize key word at the top of the Api controller.

To provide an authentication/authorization we need to use ‘Authorize’ key at the top of the action method or the controller.

If we want to provide authentication/authorization to controller level then we need to add it at the top of the controller.

If we want to provide it to action method level then we need to add it at the top of the Action method.

Step 5: How to get the access token using user credentials in ‘postman client’:

Enter the Url: http://Hostname:PortNumber /token in the post man client enter the details as heighted in the image below:

We need to pass the credentials in the body section.

Access Token:

Allows you to access your Api’s without re-entering the user’s credentials.

Each Access token has expiration time and we can set the expiration time in Startup class.

We can regenerate the access token if it is expired.

Refresh token:

If the current ‘Access Token’ is expires, then we can get the new access token by using ‘Refresh Token’.

Expires_in:

This indicate the expiration time of access token. We can customize the expiration time according to our requirements.

Token type:

This indicate the type of the token that we need to add in the header.

Step 6: How to get the new access token by using existing refresh token in ‘postman client’:

Enter the Url: http://Hostname:PortNumber /token and enter the details as shown in the image below:

Step 7: How to use the Access token to call the rest api in ‘postman client’:

Enter your Api URL and then enter the details as heighted in the image below:

Conclusion: In this article, we have discussed how we can implement token based authentication to secure the web Api’s. The main advantage of token based authentication over basic authentication is that it will avoid the users to provide their credentials multiple times in the application as we are using the access token to authenticate the user. It also provides the security for the web Api's.