:::: MENU ::::

Asp.Net Web API Token Based Authentication

Today i will try to explain how to use token based authendtication on asp.net web api 2 restful service projects. Restful service architecture very populer because it’s very light and implemantation is very easy.  Other big advantage of restful services is, it gives us a chance to service our data to all platforms including mobile devices, web projects, televisions etc.


You can see token based scenario implementation at below image

accessToken

So basicially authendtication steps are :

  • User sends creadentials to server
  • Authorization Server sends an access token if creadentials are correct
  • Users can reach other service methods with access token

 

Now its time to start sample project

We use OAuth 2.0  protocol and Microsoft Owin Library will help us. Owin is basically creating own pipeline between iis and application to manage requests.

I’ve created Asp.Net Web Application project with empty templates and Wep API core reference

project

 

We need to add Microsoft.AspNet.WebApi.Owin, Microsoft.Owin.Host.SystemWeb and Microsoft.Owin.Security.OAuth package on nuget package manager.

After this package i’ve created  folder as OAuth and i created startup.cs class with below code.

Next step i’ve created Providers folder in OAuth folder and SimpleAuthorizationServerProvider.cs class inside of Providers folder with below codes.

I just want to underline a point about above code and it’s about CORS settings.

We are saying to owin with this code restful service allow to alldomains to all requests.Finally we are ready to use token based authendtication, lets create a product controller to test our authentication service.

ProductController.cs class codes are below

 

This line says all methods of ProductController is need authentication.

When we run projects and navigate to /api/Product/List we will see below message on browser

To get a access token we have to send a request /token

with following parameters

Request headers :

Header: Accept                Value: application/json
Header: Content-Type     Value: application/x-www-form-urlencoded

Request Body :

Data-Type : x-www-form-urlencoded

Key: grant_type                 Value: password
Key: username                   Value:Username
Key: password                    Value: Password

You can find successfull postman request at below image

token

Now we are ready to new request with access token we need to add this headers to request
Header: Content-Type     Value: application/json

Header: Authorization     Value: Bearer accessTokenHere

productList

As you can see at above picture we got to product list with our secure access token. I hope this tutorial helps you.

You can find source code here : https://github.com/hamdiceylan/WebAPITokenBasedAuthentication

If you have any question about tutorial you can leave a comment.

 

 

 

 


So, what do you think ?