08Aug

Token Based Authentication for Web API's

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:

  1. Basic authentication.
  2. 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.

TokenBasedAuthorizat...

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:

  1. AuthorizationServerProvider.
  2. 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.
  • GrantResourceOwnerCredentials(): 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.
  • 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:

Token

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:

RefershToken

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:res

 

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.

Attachments

  1. WebApisTokenAuth.rar 8/8/2017 12:00:43 PM

Related

ASP.NET: Audit Trail Implementation using Entity Framework

When you are working with certain projects which involves the Customer records, you might need to tr...

Read More >

Create Restful service using Web API

What is Asp.Net Web API?Asp.Net Web API is a framework for building HTTP services that can be consum...

Read More >

Asynchronous actions in MVC 5

What does it mean?Asynchronous actions allow developers to handle more concurrent requests and can b...

Read More >

ELMAH Integration in ASP.NET MVC Application

ELMAH(Error Logging Modules And Handlers)What is ELMAH?ELMAH (Error Logging Modules and Handlers) is...

Read More >

Dependency Injection on SignalR

                &nbs...

Read More >

Create custom project templates in Visual Studio

Visual studio installation comes with the various predefined project templates, and we can use one o...

Read More >

Unit testing in .NET

Unit Testing – ExplainedA process which involves writing code to verify a system at a lower an...

Read More >

Part 2 of KnockOut.js in Asp.Net

Computed Observables:             &...

Read More >

Introduction on SignalR

Introduction on SignalRReal–Time Web ApplicationThe real-time web is a set of technologies tha...

Read More >

How to upload documents to SharePoint 2013

IntroductionSharePoint is a browser-based collaboration, content management, and extensible platform...

Read More >

Share

Post a Comment

  • Recent
  • Popular
  • Tag
Tags
Monthly Archive
Subscribe
Name

Contact Us
  • *
  • *