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
- What is Token based authentication.
- What is Cookie based authentication.
- What is Web API.
- What is Postman.
- 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
- 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.
- To support cross origin resource sharing by using NuGet package manager search for Cors and install the package. The following picture shows the package.
- Open WebApiConfig class and add the line config.EnableCors() into the Register function.
- 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>
- 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; }
}
- 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.
- 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.
- 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();
}
- Now run the project and it will open a port and will get ready to receive request from client.
- 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.
- 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.
- 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.