Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Token Based Authentication using Postman as Client and Web API 2 as Server

4.91/5 (21 votes)
4 Apr 2016CPOL4 min read 206.9K   5K  
Web service security using bearer Token with Postman as a client application and Web API as server side.

Introduction

Authentication and Authorization is a major issue when developing a web application which contains restricted resources. As we know cookie based authentication is one way of authentication that is used to access the resources of the same domain. Token based authentication is a different way of authentication which follow OAuth2 standard.  Token based authentication is useful to access the resources that are not in the same domain that means from other domains. Microsoft Web API 2 allow token bases authentication to access the restricted resources.

Contents of this article

  1. What is Token based authentication.
  2. What is Cookie based authentication.
  3. What is Web API.
  4. What is Postman.
  5. Demo project.

What is Token based authentication

Token based authentication allow client application to access the restricted resources of a server side application. Token based authentication uses a bearer token between client and server to access the resources. And to get the token, client application first send a request to Authentication server endpoint with appropriate credential. If the username and password is found correct then the Authentication server send a token to client as a response and the client application then use the token to access the restricted resources in next requests. ASP.Net Web API uses OWIN OAuth middleware for Authentication server operations.

The following diagram shows the Authentication Server representation for Web API.

Image 1

What is Cookie based authentication

I have tried to represent the cookie based authentication in the following diagram.

Image 2

In the above diagram browser send a login request to the server. Web server then use asp.net identity and OWIN middleware to check user credential. If user is valid then the server returns the requested resources  to the client and same time server send a authentication cookie to the client. The browser then includes that authentication cookie with the successive request to the server to avoid login again.

What is Web API

In short web api is a Microsoft .Net framework that provide REST-ful web services to expose data for clients. Web api provide the necessary functionality to support OAuth2 protocol for authentication. And OAuth2 provide Token based authentication for security.

What is Postman

Postman is a extension of Chrome, which is used as a client application to test the request and response between web service and client. Postman allows user to add both header and body parameters with the request. In our demo project we shall use Postman as a client app to get Token from server and next we will use this Token for authentication.

Demo project

The demo Web API project is configured to give support for Authentication server which return bearer token to client and contains weather forecast as resources  and send that data as a response to the client.

I have used VS 2013 and SQL Server 2012 for demo projects. The steps are as follows

  1. Create a new project using Asp.Net Web API template. Change the Authentication option to Individual User Accounts. It will add necessary dll such as OWIN, Identity, OAuth and will configure the Authentication Server automatically.  The solution explorer is shown below.Image 3
  2. To support cross origin resource sharing by using NuGet package manager search for Cors and install the package. The following picture shows the package.Image 4
  3. Open WebApiConfig class and add the line config.EnableCors() into the Register function.
  4. Add the following connection string in Web.config file.
    <connectionStrings>
    
        <add name="DefaultConnection" connectionString="Data Source=***;Initial Catalog=WeatherForecast;User ID=sa;Password=***" providerName="System.Data.SqlClient" />
    
      </connectionStrings>
    
  5. The new Weather model contains the Weather information.
        public class Weather
        {
            public int Id { get; set; }
            public string CountryName { get; set; }
            public string Temperature { get; set; }
        }
  6. The Get function of the new controller WeatherController, returns list of predefined weather information.
    [Authorize]
            public List<Weather> Get()
            {
                List<Weather> OrderList = new List<Weather> 
                {
                    new Weather {Id = 1, CountryName = "Dhaka, Bangladesh", Temperature = "88 F" },
                    new Weather {Id = 2, CountryName = "Washington, DC", Temperature = "65 F" },
                    new Weather {Id = 3, CountryName = "Mumbai, Maharashtra, India", Temperature = "90 F" },
                    new Weather {Id = 4, CountryName = "London, UK", Temperature = "56 F" }
                };
    
                return OrderList;
            }

    Here [Authorize] filter is used to filter the unauthorized user to access the action. So client need to pass the valid bearer token to access the resources.

  7. The default configuration for Authentication server is showing below
    static Startup()
            {
                PublicClientId = "self";
    
                UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());
    
                OAuthOptions = new OAuthAuthorizationServerOptions
                {
                    TokenEndpointPath = new PathString("/Token"),
                    Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
                    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                    AllowInsecureHttp = true
                };
            }

    The url is defined in the property TokenEndpointPath is the endpoint to request for token.

  8. The Register action of AccountController is used to create a new user in server database.
            [AllowAnonymous]
            [Route("Register")]
            public async Task<IHttpActionResult> Register(RegisterBindingModel model)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
                IdentityUser user = new IdentityUser
                {
                    UserName = model.UserName
                };
    
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);
                IHttpActionResult errorResult = GetErrorResult(result);
    
                if (errorResult != null)
                {
                    return errorResult;
                }
    
                return Ok();
            }
  9. Now run the project and it will open a port and will get ready to receive request from client.
  10. Now open the Postman from Chrome Apps list if installed and send a POST request to the server's Account controller to register a new user with username and password as a parameter. The screenshot is shown below.

    Image 5

  11. Now send a POST request to the server for the bearer token using the newly created user's username and password as a parameter. A new parameter grant_type is added with the request with value 'password'. The screenshot is shown below.Image 6
  12. The final request is a GET request to get weather info as a JSON string. This request contains a header parameter named Authorization and its value is the bearer token. The following screen shows details.Image 7

Conclusion

In conclusion this article describe token based authentication with diagram and its implementation. Token based authentication basically used for web services. Here I have used Web API As web service and Postman as a client. The demo project shows how to create a Web API project and how to apply authentication using bearer token.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)