Click here to Skip to main content
15,881,172 members
Articles / Web Development / HTML

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

Rate me:
Please Sign up or sign in to vote.
4.91/5 (21 votes)
4 Apr 2016CPOL4 min read 203.7K   5K   29   20
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)


Written By
Founder http://softwarelandmarks.com/
Bangladesh Bangladesh
I am in Software Development for more than 12 years. I am expert on Microsoft Platform for Web Forms, MVC, MVC Core, Web API, Desktop App, PHP etc. I am also expert on jQuery, AngularJS, Bootstrap, Font Awesome, Telerik UI, Kendo UI etc. I know BackboneJS, KnockoutJS also. I am an article writer. I have many articles in CodeProject.

Email: khademulbasher@gmail.com

Comments and Discussions

 
QuestionUnable to use generated token value in Postman to get weather data Pin
Member 1158699626-Aug-19 21:34
Member 1158699626-Aug-19 21:34 
QuestionIs this still valid for Core 2.2 Pin
Mycroft Holmes8-Mar-19 13:20
professionalMycroft Holmes8-Mar-19 13:20 
Questioncan't download the source Pin
Member 257544118-Nov-18 9:59
Member 257544118-Nov-18 9:59 
Praisewhere is DB Pin
Hari Velu18-Nov-18 4:29
professionalHari Velu18-Nov-18 4:29 
GeneralRe: where is DB Pin
Hari Velu18-Nov-18 4:57
professionalHari Velu18-Nov-18 4:57 
QuestionPlease provide sample javascript client code for web api Pin
Nitin S28-Jun-18 23:40
professionalNitin S28-Jun-18 23:40 
QuestionIs this token-based part for Azure/Cloud environment Pin
Member 879056319-Apr-18 11:42
Member 879056319-Apr-18 11:42 
Questionhow to use change password Pin
Sunil Chaudhary9-Oct-17 19:27
Sunil Chaudhary9-Oct-17 19:27 
QuestionHow to upload multiple file with model property in web api using postman Pin
Member 1144081625-Aug-17 7:43
Member 1144081625-Aug-17 7:43 
QuestionHow to upload multiple file with model property in web api using postman Pin
Member 1144081625-Aug-17 7:41
Member 1144081625-Aug-17 7:41 
QuestionPerfect Pin
Lungelo Nzimande22-Jul-17 19:02
Lungelo Nzimande22-Jul-17 19:02 
QuestionEcem Pin
Ecem Ecrin28-Apr-17 12:10
Ecem Ecrin28-Apr-17 12:10 
PraiseJust what I needed! Pin
Member 23932568-Apr-17 6:30
Member 23932568-Apr-17 6:30 
QuestionIn case of cookie based auth where token is stored in session cookie or normal cookie ? Pin
Tridip Bhattacharjee17-Jan-17 2:53
professionalTridip Bhattacharjee17-Jan-17 2:53 
QuestionSupport Web API (1)? Pin
inhaxiokimdu15@gmail.com31-Oct-16 17:39
inhaxiokimdu15@gmail.com31-Oct-16 17:39 
QuestionWhere is the token physically stored? Pin
Member 473692519-Oct-16 22:31
Member 473692519-Oct-16 22:31 
AnswerRe: Where is the token physically stored? Pin
sachinoncodeproject17-Mar-17 2:05
sachinoncodeproject17-Mar-17 2:05 
AnswerRe: Where is the token physically stored? Pin
Member 1158699626-Aug-19 21:36
Member 1158699626-Aug-19 21:36 
QuestionFor Post Method Pin
Payal Chaudhary26-Aug-16 1:23
Payal Chaudhary26-Aug-16 1:23 
PraiseAwesome Pin
SagarNanivadekar12-Aug-16 5:28
SagarNanivadekar12-Aug-16 5:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.