Click here to Skip to main content
13,195,379 members (66,847 online)
Click here to Skip to main content
Add your own
alternative version

Stats

88.6K views
3.4K downloads
24 bookmarked
Posted 4 Apr 2016

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

, 4 Apr 2016
Rate this:
Please Sign up or sign in to vote.
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.

What is Cookie based authentication

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

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.
  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.
  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.

  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.
  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.

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)

Share

About the Author

Khademul Basher
Team Leader Brain Station-23
Bangladesh Bangladesh
I am a Software Engineer and expert in Windows platform both for Web and Device. I develop software both for Web and devices. I like the new technologies like NodeJS and some JavaScript frameworks like AngularJS, KnockoutJS, BackboneJS. I am a quick learner and like to research and innovate.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
Questionhow to use change password Pin
Sunil Chaudhary9-Oct-17 19:27
memberSunil 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
memberMember 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
memberMember 1144081625-Aug-17 7:41 
QuestionPerfect Pin
Lungelo Nzimande22-Jul-17 19:02
memberLungelo Nzimande22-Jul-17 19:02 
QuestionEcem Pin
Ecem Ecrin28-Apr-17 12:10
memberEcem Ecrin28-Apr-17 12:10 
PraiseJust what I needed! Pin
Member 23932568-Apr-17 6:30
memberMember 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
memberinhaxiokimdu15@gmail.com31-Oct-16 17:39 
QuestionWhere is the token physically stored? Pin
Member 473692519-Oct-16 22:31
memberMember 473692519-Oct-16 22:31 
AnswerRe: Where is the token physically stored? Pin
sachinoncodeproject17-Mar-17 2:05
membersachinoncodeproject17-Mar-17 2:05 
QuestionFor Post Method Pin
Payal Chaudhary26-Aug-16 1:23
memberPayal Chaudhary26-Aug-16 1:23 
PraiseAwesome Pin
SagarNanivadekar12-Aug-16 5:28
memberSagarNanivadekar12-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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171019.1 | Last Updated 5 Apr 2016
Article Copyright 2016 by Khademul Basher
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid