Authentication in WebAPI

What is Authentication:

Authentication is process of determining that some one who is going to use the resources, is genuine person and has access right or in other way we can say Authentication is process to allow authorized user to access the resources of WebAPI rest service.

Why Authentication required:

WebAPI is used by broad range of applications and provide data to client application, so we have to secure WebAPI service.

Type o f Authentication:

1. Basic Authentication

2. Token based Authentication

We will learn basic Authentication in this tutorial.

Follow the below steps to implement basic authentication

Step 1: Create a Web API Project with name WebApiBasicAuthenticationDemo.

      • Got to File-> New-> Project-> ASP.NET Web Application –> Click “Next” button.
      • Enter project name WebApiBasicAuthenticationDemo then click “Create” button.
      • Select WebAPI then click “Create” button.

              Note: Visual studio 2019 is used to create WebAPI project.

Step 2:  Add a Class “Security” and method “Login” to authenticate user. Login method will take user name and password as parameter and it is authenticate in DB. Here username = “raj” and password = “singh”. You can verify username and password from DB using ADO.NET or entity framework.

image

Step 3: Add BasicAuthentication class with below code.

image

Here BasicAuthenticationAttribute is inheriting AuthorizationFilterAttribute and overriding OnAuthorization method. BasicAuthentication is returning username and password. This username and password  is used to verify  the  user by Login method. It will  return unauthorized,  if BasicAuthentication is not set or authentication fails.

Step 4: Add BasicAuthentication Attribute above Controller as shown below.

image

Here I am setting [BasicAuthentication] attribute to Controller label. OnAuthorization() will be called when ever any WebAPI Get/Post/Put/Delete method is called. You can set this attribute at method label also but authentication will be done for method only, not for all methods.

Step 5: Select Authorization tab in post man.

  • Select Authorization type as Basic Auth.
  • Enter user name and password as shown in below screenshot

image

Here Get method without parameter will be called and it will return array of strings as shown in above screenshot.

Thanks for reading.clip_image001

1 Comment

Leave a Reply

Your email address will not be published.


*