• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Sunday, July 26, 2020

Client Validation Using Basic Authentication in Web API

 Admin     July 26, 2020     .Net, Asp.Net, C#, Web API     No comments   

In this article, I am going to discuss how to implement Client Validation Using Basic Authentication in Web API. Please read our previous article before proceeding to this article as we are going to work the same example. In our last article, we discussed how to implement Token Based Authentication in ASP.NET Web API.

If you observed in the last article, we have created the following MyAuthorizationServiceProvider class.
Client Validation Using Basic Authentication in Web API

The first method i.e. ValidateClientAuthentication method is responsible for validating the Client, in the above example, we assume that we have only one client so we’ll always return that it is validated successfully.

Let’s change the requirement. Assume that we have more than one client, who is going to consume our service. In such a case, we need to validate the clients within the ValidateClientAuthentication method.

Let’s see how to achieve this.
For this, we are going to use the following ClientMaster table
Client Validation Using Basic Authentication in Web API

Please use below SQL Script to create and populate the ClientMaster table with some test data.
USE SECURITY_DB
GO
-- Create ClientMaster table
CREATE TABLE ClientMaster
(
  ClientKeyId INT PRIMARY KEY IDENTITY,
  ClientId VARCHAR(500),
  ClientSecret VARCHAR(500),
  ClientName VARCHAR(100),
  CreatedOn DateTime
)
GO
-- Populate the ClientMaster with test data
 INSERT INTO ClientMaster(ClientId, ClientSecret, ClientName, CreatedOn) 
 VALUES(NEWID(), NEWID(), 'My Client1', GETDATE())
 INSERT INTO ClientMaster(ClientId, ClientSecret, ClientName, CreatedOn) 
 VALUES(NEWID(), NEWID(), 'My Client2', GETDATE())
 INSERT INTO ClientMaster(ClientId, ClientSecret, ClientName, CreatedOn) 
 VALUES(NEWID(), NEWID(), 'My Client3', GETDATE())
Once you create the ClientMaster table, then you need to update the EDMX file to add the above ClientMaster table.

Create a class file with the name ClientMasterRepository.cs and then copy and paste the following code.
namespace TokenAuthenticationInWebAPI.Models
{
    public class ClientMasterRepository : IDisposable
    {
        // SECURITY_DBEntities it is your context class
        SECURITY_DBEntities context = new SECURITY_DBEntities();
        
        //This method is used to check and validate the Client credentials
        public ClientMaster ValidateClient(string ClientID, string ClientSecret)
        {
            return context.ClientMasters.FirstOrDefault(user =>
             user.ClientId == ClientID
            && user.ClientSecret == ClientSecret);
        }
        public void Dispose()
        {
            context.Dispose();
        }
    }
}
Here we create the ValidateClient method which is very straightforward. It’s the ClientID and ClientSecret as input parameter and checks in the ClientMaster table whether the client is valid or not and it simply returns the client details.

Now we need to modify the ValidateClientAuthentication() method of MyAuthorizationServerProvider class as shown below.
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
    string clientId = string.Empty;
    string clientSecret = string.Empty;
    // The TryGetBasicCredentials method checks the Authorization header and
    // Return the ClientId and clientSecret
    if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
    {
        context.SetError("invalid_client", "Client credentials could not be retrieved through the Authorization header.");
        context.Rejected();
        return;
    }
    //Check the existence of by calling the ValidateClient method
    ClientMaster client = (new ClientMasterRepository()).ValidateClient(clientId, clientSecret);
    if (client != null)
    {
        // Client has been verified.
        context.OwinContext.Set<clientmaster>("oauth:client", client);
        context.Validated(clientId);
    }
    else
    {
        // Client could not be validated.
        context.SetError("invalid_client", "Client credentials are invalid.");
        context.Rejected();
    }
    context.Validated();
}
Note: We need to pass the ClientId and ClientSecret using the Basic authentication in the authorization header i.e. in the Base64 encoded format.

Modify the GetResource1 action method of the TestController as shown below.
Client Validation Using Basic Authentication in Web API

Testing the API using Postman:
Let’s first create the Base64 Encode value by for the ClientID and ClientSecret by using the following website

https://www.base64encode.org/

Enter the ClientID and ClientSecret separated by a colon (:) in “Encode to Base64 format” textbox, and then click on the “Encode” button as shown in the below diagram which will generate the Base64 encoded value.
Client Validation Using Basic Authentication in Web API

Once you generate the Base64 encoded string, let’s see how to use basic authentication in the header to pass the Base64 encoded value.

Here we need to use the Authorization header and the value will be the Base64 encoded string followed the “BASIC” as shown below.
Authorization: BASIC QzFBMDNCMTAtN0Q1OS00MDdBLUE5M0UtQjcxQUIxN0FEOEMyOjE3N0UzMjk1LTA2NTYtNDMxNy1CQzkxLUREMjcxQTE5QUNGRg==
Let’s see step by step procedure to use the Postman to generate the Access Token
Step1:
Select the Method as POST and provide URI as shown below in the below image
Client Validation Using Basic Authentication in Web API

Step2:
Select the Header tab and provide the Authorization value as shown below.
Authorization: BASIC QzFBMDNCMTAtN0Q1OS00MDdBLUE5M0UtQjcxQUIxN0FEOEMyOjE3N0UzMjk1LTA2NTYtNDMxNy1CQzkxLUREMjcxQTE5QUNGRg==

Client Validation Using Basic Authentication in Web API

Step3:
Select the Body Tab. Then choose the x-www-form-urlencoded option and provide the username and password value. Provide the grant_type value as password as shown in the below image,
Client Validation Using Basic Authentication in Web API

Now click on the Send button which will generate the access token as shown below.
Client Validation Using Basic Authentication in Web API

Once the access token is generated, we use that token to access the resources as shown below.
Client Validation Using Basic Authentication in Web API

In the next article, I will discuss how to generate Refresh Token in ASP.NET Web API. Here, in this article, I try to explain how to implement Client Validation Using Basic Authentication in Web API with an example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Summary:
I hope this post will be helpful to understand the concept of Client Validation Using Basic Authentication in Web API
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • C# Programming Examples on Sorting
    Today i am going to tell you some of the Sorting programming questions in C#. Q1- Write a C# program to perform Selection sort. Ans:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape