The security in WebAPI is important and cookie based authentication has existed for a long time. You may be curious why we still need token based Auth and why it is becoming more and more popular in recent years.
This blog was created to guide you through some core concepts and set up a token based WebAPI plain project via OWIN within 10 minutes.
Firstly, let’s take a look at some core concepts:
Token Auth: Allows users to enter their username and password to obtain a token which allows them to fetch a specific resource without using their username and password. Once their token has been obtained, the user can offer the token – which offers access to a specific resource for a time period – to the remote site.
OWIN (Open Web Interface for .NET) defines a standard interface between .NET Web applications and Web servers, which is used for decoupling server and application. Here we mainly use its feature of authentication.
Create WebAPI token-based project Step by Step
Now we are ready to build a test project step by step. We are going to create two endpoints to test the token which are /token and api/TokenTest/Authorize:
- Create an empty WebAPI project
- Install the below packageInstall-Package Microsoft.AspNet.WebApi.Owin -Version 5.2.2
Install-Package Microsoft.Owin.Host.SystemWeb -Version 2.1.0
Install-Package Microsoft.AspNet.Identity.Owin -Version 2.0.1
Install-Package Microsoft.AspNet.Identity.EntityFramework -Version 2.0.1
Install-Package Microsoft.Owin.Security.OAuth -Version 2.1.0
Install-Package Microsoft.Owin.Cors -Version 2.1.0
- Make sure you have the following four C# files: WebApiConfig, Startup, SimpleAuthorizationServerProvider, TokenTestController. The code is pretty short, simple and self-explained.
Let’s have a test about the above-mentioned two endpoints by postman.
- Launch project and get the token by requesting /token endpoint
- Access /api/TokenTest/Authorize directly without token. It will respond 401 as expected.
- Send above request again along with the Bearer token from above #1 and respond 200 as expected.
Advantages and Disadvantages
It is very simple, right? Now you have an initial overview of Token Based Authentication which is one of the security solutions of WebAPI. Let’s continue to summarize its advantages and disadvantages compared with cookie based Authentication.
Scalable: Usually the token itself holds all encrypted user info, so adding more servers to your web farm is an easy task.
Mobile Friendly: Comparing with cookies, storing token in native mobile platforms or browsers could be a standard way.
Decoupled: Any server providing token Auth service could be an alternative option.
Safer: CSRF Attack Prevent.
Performance: Decoding token to get use info is usually faster than querying DB.
Disadvantage: Need additional code to store and send token.