This is part 3 of Web API tutorial series. In this tutorial you will learn implementing basic bearer authentication in Web API application. There are many kind of security you can implement in your Web API. In this part we will learn about bearer authentication.
In this section, we will learn how to implement bearer authentication in Web API. This is only for demostration purpose, so, we are not using any database or other medium to fetch user record and only taking hard coded username and password. Before we start, let's understand what is Bearer Authentication. You can think this as a Token Authentication where the bearer or user has a token with him and interestingly, only those are authorized who has this token with them. This is very basic kind of authentication where token can be generation using username and password or it could be a hard coded token. This token has to passed with the reqeust for authorization and once request is authorized, communication is set between client and Web API and user can get the response. Request goes to Authorization server which generated encrypted token which is also known as bearer token. This sever is also used to validate the token and authorize the bearer user.
Authorize attribute is the in-built feature to implement authentication. It works on Identity (we will cover this in later part of tutorial) and validate users on the basis of data stored in AspNetIdentity database.
System will throw 401 error if request is not authorized.
You can also create custom filter to implement authentication. In this tutorial we created CustomAuthenticationAttribute which inherits from AuthorizationFilterAttribute which is under System.Web.Http.Filters namespace. Create a class CustomAuthenticationAttribute, inherits from AuthorizationFilterAttribute and add below code into this.
Above code checks for bearer token in Authorize parameter in request header, it decrypt token and match with existing username and password. Once request is validated, communication is set between Web API and client and respose is provided else 401 error is passed back as response.
Now add this attribute in EmployeeController class in Web API application.
Now add below code in EmployeeController under MVC applicaiton inside GetEmployee() and GetEmpoyeeByID() methods. In below code, we have hard coded username and password for demonstration purpose (you can change it accordingly). We are creating encrypted token using Base64
Build the application and check the output. It should not throw any error as use has been authorized, bearer token is being passed in request header as authorize parameter which is validated at Web API side.
On thing is to note that now you cannot directly request this Web API from browser as it needs token along with the request.
Hope this helps you.