• 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

Refresh Token in Web API

 Admin     July 26, 2020     .Net, Asp.Net, C#, Web API     1 comment   

In this article, I am going to discuss how to implement Refresh Token in Web API by validating the clients, as well as I, will also discuss how to persist the refresh token into a database. Please read the following two articles before proceeding to this article as we are going to use the same example that we worked in our previous two articles.

Token Based Authentication in Web API: In this article, we discussed how to implement and use the Token Based Authentication in Web API.

Client Validation in Token Based Authentication: In this article, we discussed how to validate the clients while generating the token in Web API.

What is a Refresh Token?
A Refresh Token is a special kind of token that can be used to obtain a new renewed access token which allows access to the protected resources. You can request for the new access tokens by using the Refresh Token in Web API until the Refresh Token is blacklisted.

Why we need Refresh Token in Web API?
The idea of using the refresh token is to issue a short-lived access token (up to 30 minutes) for the first time and then use the refresh token to obtain a new access token and use that access token to access the protected resources.

So, the user needs to provide the username and password along with the client info (i.e. the client id and client secret) to authenticate himself, and if the information provided by the user is valid, then a response contains a short-lived access token along with a long-lived refresh token gets generated.

The refresh token is not an access token it is just an identifier for the access token. Now once the access token is expired, the user can use the refresh token to obtain another short-lived access token and so on.

Why not long-lived access token?
Now, you may have one question in your mind. Why not we are issuing a long-lived access token for the first time?

Let’s discuss why not a long-lived access token or what are the advantages of using refresh token in Web API. Mainly there are three main reasons to use the refresh tokens are as follows

Updating the Access Token Content:
As we already discussed, the access tokens are self-contained tokens means they contain all the information (which is known as claims) of an authenticated user once the access token is generated.

Now, if we issue a long-lived access token, let say for example 1 month, for a user let’s say “Anurag” and let say the user “Anurag” is enrolled with the role “Users” at the moment. So all this information gets stored on the access token which is generated by the Authorization Server.

If you have decided (3 days after he obtained the access token) to add him with the role “Admin” and then there is no way to update this information in the access token which is already generated, you need to ask him to re-authenticate himself again, so that the Authorization server add the updated information to the newly generated access token, and this is not feasible in most of the cases. You might not be able to reach to the users who already obtained the long-lived access tokens.

So to overcome the above issue, you need to issue short-lived access token (30 minutes for example) along with a long-lived refresh token and then the user needs to use the refresh token to obtain the newly updated access token, once the user obtains the new access token, the Authorization Server will be able to add the updated claims or new claims to the new access token being generated.

Revoking the Access from Authenticated users:
Once the user obtained the long-lived access token, then he will be able to access the server resources as long as his access token is not expired and there is no standard way to revoke the access tokens unless and until the Authorization Server implements some custom logic to store the generated access token a database and need to do database checks with each and every request.

But with the refresh token, a database or system admin can simply revoke the access by deleting the refresh token identifier from the database. So, when the user requests a new access token by using the deleted refresh token, the Authorization Server will reject this request because the refresh token is no longer available in the database.

No need to store or ask for the username and password frequently:
Using refresh token allows you to ask the user for his username and password only one time (i.e. for the first time), then the Authorization Server can issue very long-lived refresh token (1 year for example) and the user will stay logged in all this period until and unless system admin tries to revoke (delete) the refresh token. This can be very useful if you are building an API that will be consumed by a front-end application where it is not feasible to keep asking for the username/password frequently.

So for the above three major reasons we need to use Refresh Tokens.

The Refresh Tokens and Clients In order to use the refresh token, we need to be bound to the refresh token with a Client. In simple words, we can define a client as an application who wants to access our resources. Each Client should have a unique Client Id and Client Secret.

The Client Id is a piece of unique public information that identifies the application among other applications. The client id can be included in the source code of your application, but the client secret must stay confidential.

Bounding the refresh token to a client is very important this is because you do not want any refresh token generated by your Authorization Server to be used by another client to obtain the access token.

The schema for the client’s table should be as shown below.
Refresh Token in Web API

In our previous article, we create the ClientMaster table, so let’s delete the existing ClientMaster table and regenerate the ClientMaster table with the above structure.

Please use below SQL Script to DROP, Create and Populate the ClientMaster table with two different clients which we are going to use in this demo.
USE [SECURITY_DB]
GO
--First DROP ClientMaster table
DROP TABLE ClientMaster
-- Create the ClientMaster table with new structure
CREATE TABLE [ClientMaster](
  [ClientKeyId] INT PRIMARY KEY IDENTITY(1,1),
  [ClientID] VARCHAR(500) NOT NULL,
  [ClientSecret] VARCHAR(500) NOT NULL,
  [ClientName] VARCHAR(100) NOT NULL,
  [Active] BIT NOT NULL,
  [RefreshTokenLifeTime] INT NOT NULL,
  [AllowedOrigin] VARCHAR(500) NOT NULL
)
GO
-- INSERT the client details inti the ClientMaster table
INSERT INTO ClientMaster VALUES('DOTNET',NEWID(),'MyClient1',1,7200,'*')
INSERT INTO ClientMaster VALUES('Tutorials',NEWID(),'Dot Net Tutorials',1,14400,'https://dotnettutorials.net')
GO
Let’s us discuss the use of each column of ClientMaster table
The ClientID and ClientSecret columns of the ClientMaster table uniquely identify a particular client.

The Active column is also very important; if the system admin is decided to deactivate a particular client so that any new requests asking for the access token from that particular deactivated client will be rejected by the Authorization Server.

The Refresh Token Life Time column is used to set when the refresh token (not the access token) will expire in minutes.

Finally, the Allowed Origin column is used to configure the CORS and to set “Access-Control-Allow-Origin” on the back-end API.

Refresh Token Schema: As we already discussed, we need to store the refresh tokens generated by the Authorization Server into a database and this is very important to facilitate the management for refresh tokens. The schema for the Refresh Token table as shown in the below image:
Refresh Token in Web API

Please use below SQL Script to create the RefershToken table.
-- Create the RefreshToken table
CREATE TABLE RefreshToken
(
  [ID] VARCHAR(500) PRIMARY KEY,
  [UserName] VARCHAR(500),
  [ClientID] VARCHAR(500),
  [IssuedTime] DATETIME,
  [ExpiredTime] DATETIME,
  [ProtectedTicket] VARCHAR(500)
)
Let discuss the use of each column of the RefreshToken table.
The ID column of the RefreshToken table contains the hashed value of the refresh token id, the API consumer will receive and send the plain refresh token Id and the UserName column indicates to which user this refresh token belongs, and the same thing is applied for ClientID column indicating that the Token belongs to that particular clients.

By having the ClientID column, as a system admin, you can revoke (delete) the refresh token for a certain user on a certain client and keep the other refresh tokens for the same user obtained by different clients. For example, let say you have two clients having the same username, if you delete one user for a particular client, then the same user of other clients can access the refresh token.

The IssuedTime and ExpiredTime columns are for display purposes only.

Finally, the Protected Ticket column contains the magical signed string which contains a serialized representation for the ticket for a specific user, in other words, it contains all the claims and ticket properties for a user.

We have discussed enough theory, so it’s time to put all the theories into practice. So let’s discuss the step by step procedure to implement the Refresh Token in Web API. As I already told you that we are going to use the same example that we worked with our previous two articles.

Step1: Modify the EDMX file
We need to modify the EDMX file to add the newly generated RefreshToken table and we also need to update the ClientMaster table. Once you modify your EDMX file, the EDMX file should look as shown below.
Refresh Token in Web API

Step2: Modify the ClientMasterRepository class as shown below
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();
        }
    }
}
Step3: Adding a Helper class
Add a class file with the name Helper.cs and then copy and paste the following code
using System;
using System.Security.Cryptography;
namespace TokenAuthenticationInWebAPI.Models
{
    public class Helper
    {
        public static string GetHash(string input)
        {
            HashAlgorithm hashAlgorithm = new SHA256CryptoServiceProvider();
            byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(input);
            byte[] byteHash = hashAlgorithm.ComputeHash(byteValue);
            return Convert.ToBase64String(byteHash);
        }
    }
}
The above GetHash method is straightforward; it takes an input of string type and returns its hash value.

Step4: Add AuthenticationRepository class file
Add a class file with the name AuthenticationRepository.cs and then copy and paste the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TokenAuthenticationInWebAPI.Models
{
    public class AuthenticationRepository : IDisposable
    {
        SECURITY_DBEntities context = new SECURITY_DBEntities();
        //Add the Refresh token
        public async Task<bool> AddRefreshToken(RefreshToken token)
        {
            var existingToken = context.RefreshTokens.FirstOrDefault(r => r.UserName == token.UserName 
                            && r.ClientID == token.ClientID);
            if (existingToken != null)
            {
                var result = await RemoveRefreshToken(existingToken);
            }
            context.RefreshTokens.Add(token);
            return await context.SaveChangesAsync() > 0;
        }
        //Remove the Refesh Token by id
        public async Task<bool> RemoveRefreshTokenByID(string refreshTokenId)
        {
            var refreshToken = await context.RefreshTokens.FindAsync(refreshTokenId);
            if (refreshToken != null)
            {
                context.RefreshTokens.Remove(refreshToken);
                return await context.SaveChangesAsync() > 0;
            }
            return false;
        }
        //Remove the Refresh Token
        public async Task<bool> RemoveRefreshToken(RefreshToken refreshToken)
        {
            context.RefreshTokens.Remove(refreshToken);
            return await context.SaveChangesAsync() > 0;
        }
        //Find the Refresh Token by token ID
        public async Task<refreshtoken> FindRefreshToken(string refreshTokenId)
        {
            var refreshToken = await context.RefreshTokens.FindAsync(refreshTokenId);
            return refreshToken;
        }
        //Get All Refresh Tokens
        public List<refreshtoken> GetAllRefreshTokens()
        {
            return context.RefreshTokens.ToList();
        }
        public void Dispose()
        {
            context.Dispose();
        }
    }
}
The methods we add in the above AuthenticationRepository class will add support for manipulating the RefreshToken table that we have added, they are self-explanatory methods and there is nothing special about them.

Step5: Modify the Client Validation logic
Here, we need to modify the logic responsible for validating the client information whether the request needs an access token or uses a refresh token to obtain a new access token. To modify the ValidateClientAuthentication method of the MyAuthorizationServerProvider class as shown below.
public override 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.");
        return Task.FromResult<object>(null);
    }
    //Check the existence of by calling the ValidateClient method
    ClientMaster client = (new ClientMasterRepository()).ValidateClient(clientId, clientSecret);
    if (client == null)
    {
        // Client could not be validated.
        context.SetError("invalid_client", "Client credentials are invalid.");
        return Task.FromResult<object>(null);
    }
    else
    {
        if (!client.Active)
        {
            context.SetError("invalid_client", "Client is inactive.");
            return Task.FromResult<object>(null);
        }
        // Client has been verified.
        context.OwinContext.Set<clientmaster>("ta:client", client);
        context.OwinContext.Set<string>("ta:clientAllowedOrigin", client.AllowedOrigin);
        context.OwinContext.Set<string>("ta:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());
        context.Validated();
        return Task.FromResult<object>(null);
    }
}
Explanation of the above code
We are trying to get the Client ID and Client Secret from the authorization header using a basic scheme, so the user needs to send the Client ID and Client Secret in the base64 encode format (client_id:client_secret) and need to send it in the Authorization header of the HTTP Request.

Once we receive the client id and client secret, we need to check it in our database whether the client is already registered with our back-end API or not (means we need to validate the client), if it is not registered we will invalidate the context and reject the request.

If the client is registered, then we will check whether the client is active or not, if it is not active, then we will also invalidate the context and reject the request

And, if we found the client is active, then we need to store the client allowed origin and refresh token lifetime value on the Owin context (if you want then you can store all information of the client), so it will be available once we generate the refresh token.

If all is valid we mark the context as a valid context which means that client validation has passed and the flow can proceed to the next step.

Step6: Validating the Resource Owner Credentials
Once the client validation has been passed, next we need to validate the resource owner credentials i.e. the username and password are correct or not, and then we need to bound the client id to the accession generated. To do so, let’s modify the GrantResourceOwnerCredentials method of the MyAuthorizationServerProvider class as shown below.
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    ClientMaster client = context.OwinContext.Get<clientmaster>("ta:client");
    var allowedOrigin = context.OwinContext.Get<string>("ta:clientAllowedOrigin");
    if (allowedOrigin == null)
    {
        allowedOrigin = "*";
    }
    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
    UserMaster user = null;
    using (UserMasterRepository _repo = new UserMasterRepository())
    {
        user = _repo.ValidateUser(context.UserName, context.Password);
        if (user == null)
        {
            context.SetError("invalid_grant", "Provided username and password is incorrect");
            return;
        }
    }
    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    identity.AddClaim(new Claim(ClaimTypes.Role, user.UserRoles));
    identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
    identity.AddClaim(new Claim("Email", user.UserEmailID));
    var props = new AuthenticationProperties(new Dictionary<string string="">
                {
                    {
                        "client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                    },
                    {
                        "userName", context.UserName
                    }
                });
    var ticket = new AuthenticationTicket(identity, props);
    context.Validated(ticket);
}
Explanation of the Above Code:
First, we need to read the client information from the Owin context and then we add the clientAllowedOrigin value to add the header “Access-Control-Allow-Origin” to Owin context response as shown in the below image.
Refresh Token in Web API

Then we will check the username and password for the resource owner and if it is valid, then we will generate the set of claims for the above user along with authentication properties which contain the client id and username as shown in the below image.
Refresh Token in Web API

Now the access token will be generated behind the scenes when we call the context.Validated(ticket) method as shown in the below image.
Refresh Token in Web API

Step8: Implementing the TokenEndpoint method
Now we need to override the TokenEndpoint method within the MyAuthorizationServerProvider class with the following code.
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
    foreach (KeyValuePair<string string=""> property in context.Properties.Dictionary)
    {
        context.AdditionalResponseParameters.Add(property.Key, property.Value);
    }
    return Task.FromResult<object>(null);
}
The above TokenEndpoint method is adding some additional properties to the token response.

Step9: Generating Refresh Token in Web API and persisting it into a database
Now we need to generate the Refresh Token and Store it into our database inside the RefreshToken table. To do so, add a class file with the name RefreshTokenProvider.cs under the Models folder and then copy and paste the following code.
using Microsoft.Owin.Security.Infrastructure;
using System;
using System.Threading.Tasks;
namespace TokenAuthenticationInWebAPI.Models
{
    public class RefreshTokenProvider : IAuthenticationTokenProvider
    {
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            //Get the client ID from the Ticket properties
            var clientid = context.Ticket.Properties.Dictionary["client_id"];
            if (string.IsNullOrEmpty(clientid))
            {
                return;
            }
            //Generating a Uniqure Refresh Token ID
            var refreshTokenId = Guid.NewGuid().ToString("n");
            using (AuthenticationRepository _repo = new AuthenticationRepository())
            {
                // Getting the Refesh Token Life Time From the Owin Context
                var refreshTokenLifeTime = context.OwinContext.Get<string>("ta:clientRefreshTokenLifeTime");
                //Creating the Refresh Token object
                var token = new RefreshToken()
                {
                    //storing the RefreshTokenId in hash format
                    ID = Helper.GetHash(refreshTokenId),
                    ClientID = clientid,
                    UserName = context.Ticket.Identity.Name,
                    IssuedTime = DateTime.UtcNow,
                    ExpiredTime = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
                };
                //Setting the Issued and Expired time of the Refresh Token
                context.Ticket.Properties.IssuedUtc = token.IssuedTime;
                context.Ticket.Properties.ExpiresUtc = token.ExpiredTime;
                token.ProtectedTicket = context.SerializeTicket();
                var result = await _repo.AddRefreshToken(token);
                if (result)
                {
                    context.SetToken(refreshTokenId);
                }
            }
        }
        public Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            throw new NotImplementedException();
        }
        public void Create(AuthenticationTokenCreateContext context)
        {
            throw new NotImplementedException();
        }
        public void Receive(AuthenticationTokenReceiveContext context)
        {
            throw new NotImplementedException();
        }
    }
}
Explanation of the above code:
As shown above, the class RefreshTokenProvider implements the interface IAuthenticationTokenProvider, and here we need to add our refresh token generation logic inside the method CreateAsync.

Let discuss what we have done inside the CreateAsync method. First, we are getting the client id from the Ticket Properties. The following code does the above things.
Refresh Token in Web API

Next, we are generating a unique identifier for the refresh token, here, I am using Guid which is enough for this, or you can use your own unique string generation algorithm. The following code exactly does the same.
Refresh Token in Web API

Then we are reading the refresh token lifetime value from the Owin context and this value was set when we validate the client, this value will be used to determine how long the refresh token will be valid for, this should be in minutes.

Then we are setting the IssuedUtc, and ExpiresUtc values for the ticket, setting those properties will determine how long the refresh token in web API will be valid for.

After setting all context properties we are calling the context.SerializeTicket() method will be responsible to serialize the ticket content and we will be able to store this magical serialized string on to the database. The following diagram shows the above things.
Refresh Token in Web API

Now we strong the above token record into the RefreshTokens table, note that we are checking the token which will be saved on the database is unique for this Username (User) and the Client, if it not unique first we will delete the existing one and then store the new refresh token. It is better to hash the refresh token identifier before storing it, so if anyone has access to the database he will not be able to see the real refresh tokens.

Finally, we will send back the refresh token id (without hashing it) in the response body. The following does the above thing.
Refresh Token in Web API

Step10: Modifying the Start class (OwinStartup class)
We need to set the RefreshTokenProvider class within the OAuthAuthorizationServerOptions, so open the class Start which is present inside the app_start folder and replace the code used to set OAuthAuthorizationServerOptions, with the below code, you can notice that we are setting the access token lifetime to a short period now (30 minutes) instead of 24 hours.
using System;
using Microsoft.Owin;
using Owin;
using TokenAuthenticationInWebAPI.Models;
using Microsoft.Owin.Security.OAuth;
using System.Web.Http;
[assembly: OwinStartup(typeof(TokenAuthenticationInWebAPI.App_Start.Startup))]
namespace TokenAuthenticationInWebAPI.App_Start
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        { 
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                //The Path For generating the Toekn
                TokenEndpointPath = new PathString("/token"),
                //Setting the Token Expired Time (30 minutes)
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                //MyAuthorizationServerProvider class will validate the user credentials
                Provider = new MyAuthorizationServerProvider(),
                //For creating the refresh token and regenerate the new access token
                RefreshTokenProvider = new RefreshTokenProvider()
            };
            
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            
            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
        }
    }
}
Step11: 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 Client ID and Client Secret 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.

Example: ClientID: DOTNET and Client Secret: EEF47D9A-DBA9-4D02-B7B0-04F4279A6D20
Refresh Token in Web API

Base64 Code value: RE9UTkVUOkVFRjQ3RDlBLURCQTktNEQwMi1CN0IwLTA0RjQyNzlBNkQyMA==

Once you generate the Base64 encoded value, 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 RE9UTkVUOkVFRjQ3RDlBLURCQTktNEQwMi1CN0IwLTA0RjQyNzlBNkQyMA==

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
Refresh Token in Web API

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

Authorization: BASIC RE9UTkVUOkVFRjQ3RDlBLURCQTktNEQwMi1CN0IwLTA0RjQyNzlBNkQyMA==
Refresh Token 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 a password as shown in the below image.
Refresh Token in Web API

Now click on the Send button which will generate the access token along with the refresh token as shown below.
Refresh Token in Web API

As shown in the response body, you will notice that we have obtained a refresh_token along with the access token which should be used to obtain a new access token (we will discuss this after a while in this post) this token is bounded to the user Anurag and for the Client DOTNET. Note that the expires_in value is related to the access token, not the refresh token, this access token will expire in 30 mins.

Step12: Generating an Access Token using the Refresh Token in Web API
Now we need to implement the logic needed to generate a new access token when we receive the request from the refresh the token, to do so open the class RefreshTokenProvider and implement the ReceiveAsync method as shown below.
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
    var allowedOrigin = context.OwinContext.Get< string>("ta:clientAllowedOrigin");
    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
    string hashedTokenId = Helper.GetHash(context.Token);
    using (AuthenticationRepository _repo = new AuthenticationRepository())
    {
        var refreshToken = await _repo.FindRefreshToken(hashedTokenId);
        if (refreshToken != null)
        {
            //Get protectedTicket from refreshToken class
            context.DeserializeTicket(refreshToken.ProtectedTicket);
            var result = await _repo.RemoveRefreshTokenByID(hashedTokenId);
        }
    }
}
Explanation of the above method:
We need to set the “Access-Control-Allow-Origin” header by getting the value from the Owin Context. If you will not set this value, then you will get 405 status code and this is because the method “GrantResourceOwnerCredentials” where we set this header is never get executed once we request the access token using the refresh tokens (grant_type = refresh_token).

Then we get the refresh token id from the request, hash this id and look for the token using the hashed refresh token id in “RefreshToken” table, if the refresh token is found, we will use the magical signed string which contains a serialized representation for the ticket to building the ticket and identities for the user mapped to this refresh token.

Finally, we will remove the existing refresh token from the “RefreshToken” table because in our logic we are allowing only one refresh token per user and client.

Implementing GrantRefreshToken in Web API
Now the request context contains all the claims stored previously for this use. Now we need to implement the logic which will allows us to issue new claims or updating the existing claims and contain them into the new access token generated before sending it to the user, to do so open class MyAuthorizationServerProvider and implement method GrantRefreshToken with the following code.
public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
{
    var originalClient = context.Ticket.Properties.Dictionary["client_id"];
    var currentClient = context.ClientId;
    if (originalClient != currentClient)
    {
        context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
        return Task.FromResult<object>(null);
    }
    // Change auth ticket for refresh token requests
    var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
    newIdentity.AddClaim(new Claim("newClaim", "newValue"));
    var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);
    context.Validated(newTicket);
    return Task.FromResult<object>(null);
}
Explanation of the above code:
First, we are reading the client id value from the original ticket and this is the client ids which get stored in the magical signed string. Then we are comparing this client id with the client id sent with the request, if they are different then we will reject this request because we need to make sure that the refresh token used here is bound to the same client when it was generated.

Now, we have the chance to add new claims or remove or update existing claims, to do this we are calling the “context.Validated(newTicket)” method which will generate the new access token and return it in the response body.

Lastly, after this method executes successfully, the flow for the code will hit the “CreateAsync” method which is present in the class “RefreshTokenProvider” and a new refresh token is generated and returned in the response along with the new access token.

Testing the Refresh Token in Web API with Postman to generate new access Token:
Step1: Select the Method as POST and provide URI as shown below in the below image
Refresh Token in Web API

Step2: Select the Header tab and provide the Authorization value as shown below. This is the Base64 encoded value for the ClientID and Client Secret.

Authorization: BASIC RE9UTkVUOkVFRjQ3RDlBLURCQTktNEQwMi1CN0IwLTA0RjQyNzlBNkQyMA==
Refresh Token in Web API

Step3: Select the Body Tab. Then choose the x-www-form-urlencoded option and provide the Refresh_Token value and the grant_type value as refresh_token as shown in the below image.
Refresh Token in Web API

In the next article, I am going to discuss how to use the Refresh Token in different types of Client Applications. We will discuss how to use it from C# and JavaScript clients. Here, in this article, I try to explain how to implement Refresh Token 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 Refresh Token in Web API
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

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 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Token Based 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 Token Based Authentication in Web API to secure the server resources with an example. Please read our previous article where we discussed how to implement Client-Side HTTP Message Handler with some examples. As part of this article, we are going to discuss the following pointers.
  1. Why do we need Token Based Authentication in Web API?
  2. Advantages of using Token Based Authentication in ASP.NET Web API
  3. How does the Token-Based Authentication work?
  4. Implementing Token-Based Authentication in Web API.
  5. Testing the Token Authentication using Postman.
Why do we need Token Based Authentication in Web API?
The ASP.NET Web API is an ideal framework, provided by Microsoft that, to build Web API’s, i.e. HTTP based services on top of the .NET Framework. Once we develop the services using Web API then these services are going to be consumed by a broad range of clients, such as
  1. Browsers
  2. Mobile applications
  3. Desktop applications
  4. IOTs, etc.
Nowadays, the use of WEB API is increasing in a rapid manner. So as a developer you should know how to develop Web APIs. Only developing Web APIs is not enough if there is no security. So, it also very important for us as a developer to implement security for all types of clients (such as Browsers, Mobile Devices, Desktop applications, and IoTs) who are going to use our Web API services.

The most preferred approach nowadays to secure the Web API resources is by authenticating the users in Web API server by using the signed token (which contains enough information to identify a particular user) which needs to be sent to the server by the client with each and every request. This is called the Token-Based Authentication approach.

How does the Token-Based Authentication work?
In order to understand how the token-based authentication works, please have a look at the following diagram.
How does the Token-Based Authentication work

The Token-Based Authentication works as Follows:
  1. The user enters his credentials (i.e. the username and password) into the client (here client means the browser or mobile devices, etc).
  2. The client then sends these credentials (i.e. username and password) to the Authorization Server.
  3. Then the Authorization Server authenticates the client credentials (i.e. username and password) and generates and returns an access token. This Access Token contains enough information to identify a user and also contains the token expiry time.
  4. The client application then includes the Access Token in the Authorization header of the HTTP request to access the restricted resources from the Resource Server until the token is expired.
Note: If this not clear at the moment then don’t worry, we will explain the above-mentioned points one by one in detail with example.

Let’s discuss the step by step procedure to implement Token-Based Authentication in Web API and then we will also how to use the token-based authentication to access restricted resources using Postman and Fiddler.

Step1: Creating the required database
We are going to use the following UserMaster table in this demo.
Token-Based Authentication in Web API

Please use below SQL Script to create and populate the UserMaster table with the required sample data.
CREATE DATABASE SECURITY_DB
GO
USE [SECURITY_DB]
CREATE TABLE UserMaster
(
  UserID INT PRIMARY KEY,
  UserName VARCHAR(50),
  UserPassword VARCHAR(50),
  UserRoles VARCHAR(500),
  UserEmailID VARCHAR(100),
)
GO
INSERT INTO UserMaster VALUES(101, 'Anurag', '123456', 'Admin', 'Anurag@g.com')
INSERT INTO UserMaster VALUES(102, 'Priyanka', 'abcdef', 'User', 'Priyanka@g.com')
INSERT INTO UserMaster VALUES(103, 'Sambit', '123pqr', 'SuperAdmin', 'Sambit@g.com')
INSERT INTO UserMaster VALUES(104, 'Pranaya', 'abc123', 'Admin, User', 'Pranaya@g.com')
GO
Step2: Creating an empty Web API Project with the name TokenAuthenticationWEBAPI
Go to the File menu > create > project > here select “asp.net web application” under the web. Provide the application name as TokenAuthenticationWEBAPI and select the project location where you want to create the project. Then click on the OK button as shown in the below image.
Creating an empty Web API Project with the name TokenAuthenticationWEBAPI

Once you click on the OK button, then a new window will open with Name New ASP.NET Web Application for selecting the Project Templates and from this window, you need to select the Empty project template as we are going to do everything from scratch and then checked the MVC and Web API checkbox from Add folder and core references for and then click on the OK button as shown in the below image.
ASP.NET Web API Token-Based Authentication

Step3: Add the required references from NuGet packages into your application.
In order to Implement the Token-Based Authentication in ASP.NET Web API, we need to install the following references from NuGet packages. Later part of this article, we will discuss the use of each the below packages.
  1. Microsoft.Owin.Host.SystemWeb
  2. Microsoft.Owin.Security.OAuth
  3. Microsoft.Owin.Cors
  4. Newtonsoft.json
For adding the above references from NuGet, Go to Solution Explorer > Right Click on the References > Click on Manage NuGet Packages > Search for the Microsoft.Owin.Host.SystemWeb, Microsoft.Owin.Security.OAuth, Microsoft.Owin.Cors and Newtonsoft.json and install.

Note: When you install the above packages the dependency references are also automatically installed into your application.

Step4: Creating the ADO.NET Entity Data Model
Here we are going to use the DB First Approach of Entity Framework to create the Entity Data Model against the SECURITY_DB database which we have already created and then select the UserMaster table from the SECURITY_DB database.

Step5: Create a Repository class
Now, you need to create a class with the name UserMasterRepository which will validate the user and also returns the user information. As you can see in the below code, the ValidateUser method takes the username and password as input parameter and then validate this. If the username and password valid then it will return UserMaster object else it will return null. Later we will discuss when and where we will use this method.
namespace TokenAuthenticationInWebAPI.Models
{
    public class UserMasterRepository : IDisposable
    {
        // SECURITY_DBEntities it is your context class
        SECURITY_DBEntities context = new SECURITY_DBEntities();
        //This method is used to check and validate the user credentials
        public UserMaster ValidateUser(string username, string password)
        {
            return context.UserMasters.FirstOrDefault(user =>
            user.UserName.Equals(username, StringComparison.OrdinalIgnoreCase)
            && user.UserPassword == password);
        }
        public void Dispose()
        {
            context.Dispose();
        }
    }
}
Step6: Add a class for validating the user credentials asking for tokens.
Now we need to add a class with the name MyAuthorizationServerProvider into our application. Within that class, we need to write the logic for validating the user credentials and generating the access token.

We need to inherit the MyAuthorizationServerProvider class from OAuthAuthorizationServerProvider class and then need to override the ValidateClientAuthentication and GrantResourceOwnerCredentials method. So, before proceeding and overriding these two methods, let us first understand what exactly these methods are going to perform.

ValidateClientAuthentication Method:
The ValidateClientAuthentication method is used for validating the client application. For the sake of simplicity, we will discuss what is a client and how to validate a client in more detail in the next article.

GrantResourceOwnerCredentials Method:
The GrantResourceOwnerCredentials method is used to validate the client credentials (i.e. username and password). If it found the credentials are valid, then only it generates the access token. The client then using this access token can access the authorized resources from the Resource Server.

As we already discussed, the signed access token contains enough information to identify a user. Now the question is how. Let me discuss this in detail.

First, we need to create an instance of the ClaimsIdentity class and to the constructor of the ClaimsIdentity class, we need to pass the authentication type. As we are going to use the Token-Based Authentication, so the Authentication Type is “bearer token”.

Once we create the ClaimsIdentity instance, then need to add the claims such as Role, Name, and Email, etc to the ClaimsIdentity instance. These are the user information that is going to be included in the signed access token. You can add any number of claims and once you add more claims. the token size will increase.

MyAuthorizationServerProvider
Create a class file with the name MyAuthorizationServerProvider.cs and then copy and paste the following code in it.
using Microsoft.Owin.Security.OAuth;
using System.Security.Claims;
using System.Threading.Tasks;
namespace TokenAuthenticationInWebAPI.Models
{
    public class MyAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (UserMasterRepository _repo = new UserMasterRepository())
            {
                var user = _repo.ValidateUser(context.UserName, context.Password);
                if (user == null)
                {
                    context.SetError("invalid_grant", "Provided username and password is incorrect");
                    return;
                }
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Role, user.UserRoles));
                identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                identity.AddClaim(new Claim("Email", user.UserEmailID));
                context.Validated(identity);
            }
        }
    }
}
Step7: Add the OWINStartup class.
Now we need to add the OWINStartup class where we will configure the OAuth Authorization Server. This is going to be our authorization server.

To do so, go to the Solution Explorer > Right Click on Project Name form the Solution Explorer > Add > New Item > Select OWIN Startup class > Enter the class name as Startup.cs > and then click on the Add button as shown in the below image.
Token-Based Authentication in ASP.NET Web API

Once you created the Owin Startup class, copy and paste the below code in it.
using System;
using Microsoft.Owin;
using Owin;
using TokenAuthenticationInWebAPI.Models;
using Microsoft.Owin.Security.OAuth;
using System.Web.Http;
[assembly: OwinStartup(typeof(TokenAuthenticationInWebAPI.App_Start.Startup))]
namespace TokenAuthenticationInWebAPI.App_Start
{
    // In this class, we will Configure the OAuth Authorization Server.
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Enable CORS (cross origin resource sharing) for making request using browser from different domains
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                //The Path For generating the Toekn
                TokenEndpointPath = new PathString("/token"),
                //Setting the Token Expired Time (24 hours)
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                //MyAuthorizationServerProvider class will validate the user credentials
                Provider = new MyAuthorizationServerProvider()
            };
            //Token Generations
            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            
            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
        }
    }
}
Understanding the Owin Startup class code:
Here we created a new instance of the OAuthAuthorizationServerOptions class and then set its options as follows:
  1. Here, we set the path for generating the tokens as “http://localhost:portnumber/token”. Later we will see how to issue an HTTP Post request to generate the access token.
  2. We have specified the expiry time for the access token as 24 hours. So if the user tried to use the same access token after 24 hours from the issue time, then this request will be rejected and HTTP status code 401 will be returned.
  3. We also specified the implementation on how to validate the client credentials for users asking for the access tokens in the custom class named MyAuthorizationServerProvider.
Finally, we passed the options to the extension method UseOAuthAuthorizationServer which will add the authentication middleware to the pipeline.

Step8: Add a Web API Controller.
Now we need to create Web API resources. To do so, add an empty Web API Controller, where we will add some action methods so that we can check the Token-Based Authentication is working fine or not.

Go to Solution Explorer > Right click on the Controllers folder > Add > Controller > Select WEB API 2 Controller – Empty > Click on the Add button. > Enter the controller name as TestController.cs > finally click on the Add button which will create the TestController.

Once you created the TestController, then copy and paste the following code.
using System.Linq;
using System.Security.Claims;
using System.Web.Http;
namespace TokenAuthenticationInWebAPI.Controllers
{
    public class TestController : ApiController
    {
        //This resource is For all types of role
        [Authorize(Roles = "SuperAdmin, Admin, User")]
        [HttpGet]
        [Route("api/test/resource1")]
        public IHttpActionResult GetResource1()
        {
            var identity = (ClaimsIdentity)User.Identity;
            return Ok("Hello: " + identity.Name);
        }
        //This resource is only For Admin and SuperAdmin role
        [Authorize(Roles = "SuperAdmin, Admin")]
        [HttpGet]
        [Route("api/test/resource2")]
        public IHttpActionResult GetResource2()
        {
            var identity = (ClaimsIdentity)User.Identity;            
            var Email = identity.Claims
                      .FirstOrDefault(c => c.Type == "Email").Value;
            var UserName = identity.Name;
            
            return Ok("Hello " + UserName + ", Your Email ID is :" + Email);
        }
        //This resource is only For SuperAdmin role
        [Authorize(Roles = "SuperAdmin")]
        [HttpGet]
        [Route("api/test/resource3")]
        public IHttpActionResult GetResource3()
        {
            var identity = (ClaimsIdentity)User.Identity;
            var roles = identity.Claims
                        .Where(c => c.Type == ClaimTypes.Role)
                        .Select(c => c.Value);
            return Ok("Hello " + identity.Name + "Your Role(s) are: " + string.Join(",", roles.ToList()));
        }
    }
}
Here, in the above controller, we have created three resources as follows,
  1. /api/test/resource1 – This resource can be accessed by all three types of roles such as Admin, SuperAdmin, and User
  2. /api/test/resource2 – This resource can be accessed by the users who are having the roles Admin and SuperAdmin
  3. /api/test/resource3 – This resource can be accessed only by the users who are having the role SuperAdmin
To test this we are going to use a client tool called Postman. First, you need to run your Web API application. If you are new to Postman then please read the following where we discussed how to use Postman to test Web API rest services.

How to use Postman to test Rest Services?

Step9: Testing the Token Authentication
Test1: Without Access Token, try to make a request for following URI

http://localhost:xxxxx/api/test/resource1

You need to change the port number. You have to provide the port number where your Web API application is running.
Securing Web API Resouces Using Token-Based Authentication

As expected you got 401 unauthorized responses

Test2: Try to create the Access token with invalid credentials
As we don’t have any user with the name test, so let’s try to create the Access Token for the test user. Select the method type as POST (1), enter the URL as http://localhost:PortNumber/token (2) and then click on body tab (3) and then select x-www-form-urlencoded (4) and then enter 3 parameters (5)
  1. username (value : test)
  2. password (value: test)
  3. grant_type (value: password)
And then click on the Send button (6).
Securing Web API Resources Using Token-Based Authentication

Once you click on the send button, you will get status as 400 Bad Request as expected and it also tells that in the error description that the provided username and password are incorrect. Let’s generate the access token with valid credentials for the user Anurag whose password us 123456 as shown in the below image.
Authentication in Web API

As you can see when you click on the send button, you will get status code 200 Ok along with you will get the access token which contains enough information to identify the user Anurag. You can also see in the Response section that the token type is Bearer and the token expire time in seconds.

Test3: Access restricted resources with the access token.

/api/test/resource2

First copy the access token that we just generated in the previous example that we are going to use the token as shown below.

Authorization: Bearer Access_Token(value)
Authentication in Web API

You can see that, when you click on the Send button, you will get 200 Ok as expected because the resource /api/test/resource2 has been accessed by the Roles Admin and SuperAdmin and here the user Anurag has the Role Admin so, we get the above response.

But the above user cannot access the resource /api/test/resource3 because the resource3 can only be accessed by the user whose role is SuperAdmin. Let’s prove this.
Web API Token-Based Authentication

As you can see, the response is 401 unauthorized. But you generate the token for the user whose Role is SuperAdmin, then you can access this resource.
Let’s have a look at the MyAuthorizationServiceProvider class
Web API Token-Based Authentication

The first method i.e. ValidateClientAuthentication method is responsible for validating the Client, in this example, we assume that we have only one client so we’ll always return that it is validated successfully. But in real-time you may have multiple clients and you need to validate the clients. So In the next article, we will discuss how to use the ValidateClientAuthentication method to validate the client.

Advantages of using Token Based Authentication in ASP.NET Web API:
Scalability of Servers:
The token which is sent to the server by the client is self-contained means it holds enough data to identify the user needed for authentication. As a result, you can add easily more servers to your web farm, there is no dependent on shared session stores.

Loosely Coupling:
The client application is not tied or coupled with any specific authentication mechanism. The token is generated, validated and perform the authentication are done by the server only.

Mobile-Friendly:
The Cookies and browsers like each other, but handling the cookies on native platforms like Android, iOS, Windows Phone is not an easy task. The token-based approach simplifies this a lot.

In the next article, I am going to discuss Client Validation Using Basic Authentication in Web API with an example. In this article, I try to explain how to implement Token Based Authentication in Web API with an example. I hope you enjoy this article.

Summary:
I hope this post will be helpful to understand how to use Token Based Authentication in Web API
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

HTTP Client Message Handler in Web API

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

In this article, I am going to discuss HTTP Client Message Handler in Web API with real-time examples. As we already discussed in HTTP Message Handler Article that a Message Handler is a class that receives an HTTP request and returns an HTTP response. The Message handler is derived from the abstract HttpMessageHandler class. There are two types of HTTP Message Handlers as follows
  1. The Server Side HTTP Message Handlers – we already discussed
  2. Client-Side HTTP Message Handlers – will discuss in this article
HTTP Client Message Handlers in Web API
The HttpClient class uses a message handler to process the requests on the client-side. The default handler provided by the dot net framework is HttpClientHandler. This HTTP Client Message Handler sends the request over the network and also gets the response from the server. As a developer if you want, then you can also create your own custom message handlers and then insert the custom message handlers into the pipeline on the client-side as shown in the below image.
HTTP Client Message Handler

Creating a Custom HTTP Client Message Handler:
Let us discuss how to create a Custom HTTP Client Message Handler. To create a custom HTTP Client message handler, what we need to do is, we need to create a custom class and that class should be derived from the System.Net.Http.DelegatingHandler class. Then the class should override the SendAsync method. The signature of the SendAsync method as following:
HTTP Client Message Handler

The SendAsync method takes an HttpRequestMessage as input and asynchronously returns an HttpResponseMessage. A typical implementation does the following:
  1. Process the request message.
  2. Call the base.SendAsync method to send the request to the inner handler.
  3. The inner handler returns a response message. (This step is asynchronous.)
  4. Process the response message and returns the response to the caller.
Creating a Custom Message Handler:
The following example shows the creation of a custom message handler which adds a custom header to the outgoing request:
using System.Net.Http;
using System.Threading.Tasks;
namespace ClientSideMessageHandler.Models
{
    class MessageHandler1 : DelegatingHandler
    {
        private int _count = 0;
        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            System.Threading.Interlocked.Increment(ref _count);
            request.Headers.Add("X-Custom-Header", _count.ToString());
            return base.SendAsync(request, cancellationToken);
        }
    }
}
The call to the base.SendAsync method is asynchronous. If your handler going to do some work after this call, then use the await keyword to resume execution after the method completes.

The following example shows a handler that logs error codes. The example shows how to get at the response inside the handler.
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace ClientSideMessageHandler.Models
{
    class LoggingHandler : DelegatingHandler
    {
        StreamWriter _writer;
        public LoggingHandler(Stream stream)
        {
            _writer = new StreamWriter(stream);
        }
        protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken);
            if (!response.IsSuccessStatusCode)
            {
                _writer.WriteLine("{0}\t{1}\t{2}", request.RequestUri,
                    (int)response.StatusCode, response.Headers.Date);
            }
            return response;
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _writer.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
Adding Message Handlers to the Client Pipeline
To add a custom message handlers to HttpClient pipeline, we need to use the HttpClientFactory.Create a method as shown below.
HttpClient client = HttpClientFactory.Create(new MessageHandler1(), new MessageHandler2());
The Message handlers are called in the order that we pass them into the Create method of the HttpClientFactory class. The reason is handlers are nested the response message travels in the other direction. That is, the last handler is the first to get the response message.

In the next article, I am going to discuss How to Implement the Token-Based Authentication in ASP.NET Web API. Here, in this article, I try to explain HTTP Client Message Handler in Web API with some examples. 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 HTTP Client Message Handler in Web API
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Basic Authentication Using Message Handler 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 Basic Authentication Using Message Handler in ASP.NET Web API. Please read our last article, where I discussed the Server-Side HTTP Message Handler in ASP.NET Web API.

As we already discussed, the basic authentication says that the client needs to send the username and password in base64 encoded format in the authorization header of the HTTP request. The server then gets the username and password from the authorization header. Once the username and password get from the header, then the server check and match the credentials with any persistent storage (most of the time it may be a database). If the credentials are found in the persistent storage then the server will treat that HTTP request as a valid request and process it else it simple return unauthorized response to the client.

Let’s us implement Basic Authentication Using Message Handler
We are going to use the following UserMaster table in this demo
Basic Authentication Using Message Handler in ASP.NET Web API

Please use below SQL Script to create and populate the UserMaster table with the required sample data.
CREATE DATABASE SECURIRT_DB
GO
USE [SECURIRT_DB]
CREATE TABLE UserMaster
(
  UserID INT PRIMARY KEY,
  UserName VARCHAR(50),
  UserPassword VARCHAR(50),
  UserRoles VARCHAR(500),
  UserEmailID VARCHAR(100),
)
GO
INSERT INTO UserMaster VALUES(101, 'Anurag', '123456', 'Admin', 'Anurag@g.com')
INSERT INTO UserMaster VALUES(102, 'Priyanka', 'abcdef', 'User', 'Priyanka@g.com')
INSERT INTO UserMaster VALUES(103, 'Sambit', '123pqr', 'SuperAdmin', 'Sambit@g.com')
INSERT INTO UserMaster VALUES(104, 'Pranaya', 'abc123', 'Admin, User', 'Pranaya@g.com')
GO
Let’s create an empty Web API application with the name BasicAuthenticationUsingMessageHandler (you can give any name) and select empty and Web API as shown in the below image.
Basic Authentication Using Message Handler in ASP.NET Web API

Once you click on the OK button, it will create the application for us. Then the next step is to create an ADO.NET Entity Data Model against the SecurityDB and Select the UserMaster table.

Here you need to choose the DB First Approach of Entity Framework.

Let’s create a class with the name ValidateUser and copy and paste the following code.
namespace BasicAuthenticationUsingMessageHandler.Models
{
    public class ValidateUser
    {
        //This method is used to check the user credentials
        public UserMaster CheckUserCredentials(string username, string password)
        {
            // SECURIRT_DBEntities it is your context class
            using (var context = new SECURIRT_DBEntities())
            {
                return context.UserMasters.FirstOrDefault(user =>
                user.UserName.Equals(username, StringComparison.OrdinalIgnoreCase)
                && user.UserPassword == password);
            }
        }
    }
}
In the above class, we create one method i.e. CheckUserCredentials which will validate the user by checking the username and password.

Now, let’s implement our own custom message handler to check whether or not the client has sent an Authorization header along with the HTTP request, if it is presented then we will check the header value against the persistent storage, in our case, it’s the database table.

So let’s create a class with the name BasicAuthenticationMessageHandler and copy and paste the following code.

BasicAuthenticationMessageHandler.cs
namespace BasicAuthenticationUsingMessageHandler.Models
{
    public class BasicAuthenticationMessageHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            try
            {
                var authenticationToken = request.Headers.GetValues("Authorization").FirstOrDefault();
                if (authenticationToken != null)
                {
                    byte[] data = Convert.FromBase64String(authenticationToken);
                    string decodedAuthenticationToken = Encoding.UTF8.GetString(data);
                    string[] UsernamePasswordArray = decodedAuthenticationToken.Split(':');
                    string username = UsernamePasswordArray[0];
                    string password = UsernamePasswordArray[1];
                    UserMaster ObjUser = new ValidateUser().CheckUserCredentials(username, password);
                    if (ObjUser != null)
                    {
                        var identity = new GenericIdentity(ObjUser.UserName);
                        identity.AddClaim(new Claim("Email", ObjUser.UserEmailID));
                        IPrincipal principal = new GenericPrincipal(identity, ObjUser.UserRoles.Split(','));
                        Thread.CurrentPrincipal = principal;
                        if (HttpContext.Current != null)
                        {
                            HttpContext.Current.User = principal;
                        }
                        return base.SendAsync(request, cancellationToken);
                    }
                    else
                    {
                        var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                        var tsc = new TaskCompletionSource<HttpResponseMessage>();
                        tsc.SetResult(response);
                        return tsc.Task;
                    }
                }
                else
                {
                    var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
                    var tsc = new TaskCompletionSource<HttpResponseMessage>();
                    tsc.SetResult(response);
                    return tsc.Task;
                }
            }
            catch
            {  
                var response = new HttpResponseMessage(HttpStatusCode.Forbidden);
                var tsc = new TaskCompletionSource<HttpResponseMessage>();
                tsc.SetResult(response);
                return tsc.Task;
            }
        }
    }
}
Please add the following namespaces:
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
Explanation of the above code:
If the Authorization header is not present in the HTTP request then it will be considered as a forbidden request but if it is present then we will get the header value. Once we get the header value then we need to decode as the value of the header is comes in encoded. Here we will use the Base64 encoding scheme in the attached header.

Once we get the user credentials then we will check the credentials and if the credentials are present in the database then we will consider it as a valid user and we will set the user principals along with the current thread.

The request will then be redirected towards a specific controller and action. Register the custom handler in the WebApiConfig file as shown in the below diagram.
Basic Authentication Using Message Handler in ASP.NET Web API

That’s it. We are done with our implementation. Let’s create one empty Web API controller and then copy and paste the following code.
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Web.Http;
namespace BasicAuthenticationUsingMessageHandler.Controllers
{
    public class TestController : ApiController
    {
        [Authorize(Roles = "Admin,User")]
        public HttpResponseMessage Get()
        {
            //You can implement your own logic
            //Get the Identity Name
            string username = Thread.CurrentPrincipal.Identity.Name;
            
            return Request.CreateResponse(HttpStatusCode.OK, "User Name = "+ username);
        }
        [Authorize(Roles = "Admin")]
        public HttpResponseMessage Post()
        {
            string username = Thread.CurrentPrincipal.Identity.Name;
            return Request.CreateResponse(HttpStatusCode.OK, "User Name = " + username);
        }
    }
}
As you can see in the above controller, both the Get and Post are decorated with an Authorise attribute and we have specified the role over each action. So, the specific roles can access a specific action. Since the Get() is to read the data, generally both the Admin and the User can access it but a Post is only allowed for an Admin.

Testing using Postman
First, let’s test for the following user

UserName: Priyanka

Password: abcdef

The username and password need to be a colon (:) separated and must be in base64 encoded. To do this use the following website

https://www.base64encode.org/

Enter the username and password 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.
Basic Authentication Using Message Handler in ASP.NET Web API

Once you generated 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 as shown below.

Authorization: UHJpeWFua2E6YWJjZGVm

GET Request:
Basic Authentication Using Message Handler in ASP.NET Web API

As you can see, we get Status 200 as expected as the user Priyanka has the role “User” and the role “User” has access to the Get Method of the Test Controller.

POST Request:
Basic Authentication Using Message Handler in ASP.NET Web API

As you can see, we get Status 401 Unauthorized as expected as the user Priyanka has the role “User” and the role “User” does not have access to the Post Method of the Test Controller.

In the next article, I am going to discuss HTTP Client Message Handler with some examples. Here, in this article, I try to explain the Basic Authentication Using Message Handler step by step 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 how to use Basic Authentication Using Message Handler in Web API
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Saturday, July 25, 2020

Server-Side HTTP Message Handlers in WEB API

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

In this article, I am going to discuss the Server-Side HTTP Message Handlers in WEB API with some real-time examples. Please read our previous article where we discussed How to Consume Web API Services with Basic Authentication. As part of this article, we are going to discuss the following important concepts related to Message handlers.
  1. What is an HTTP Message handler in ASP.NET Web API Application?
  2. Understanding Delegating Handler in Web API.
  3. Different Types of HTTP Message Handlers in Web API.
  4. Understanding Server-Side HTTP Message Handlers in Web API,
  5. How to Create Custom Server-Side HTTP Message Handlers in Web API?
  6. How to add Custom HTTP Message Handlers to the Pipeline.
  7. Different Types of Examples to understand the HTTP Message Handlers.
What is an HTTP Message handler in ASP.NET Web API Application?
An HTTP Message Handler in Web API is a class that receives an HTTP request and returns an HTTP response. The Message Handler is derived from the abstract HttpMessageHandler class.

Understanding Delegating Handler in Web API:
To handle the HTTP Request and to generate the HTTP Response in WeB API, a series of message handlers are chained together. The first handler in the chain receives the HTTP request. Do some processing, and gives the request to the next handler. At some point, the response is generated and goes back up in the chain. This pattern is called a delegating handler. The following diagram shows this process.
Server-Side HTTP Message Handlers in WEB API

What are the Different Types of HTTP Message Handlers available in ASP.NET Web API?
In ASP.NET Web API Framework, there are two types of message handlers are available. They are as follows
  1. Server-Side HTTP Message Handlers
  2. Client-Side HTTP Message Handlers
In this article, I am going to discuss the Server-Side HTTP Message Handlers in Web API Framework with some real-time examples. In our upcoming article, I will discuss the Client-Side HTTP Message Handlers in Web API.

Understanding Server-Side HTTP Message Handlers in Web API
On the server-side, The Web API Framework uses some built-in message handlers which are as follows:
  1. HttpServer: This built-in message handler gets the request from the host.
  2. HttpRoutingDispatcher: This message handler dispatches the request based on the route.
  3. HttpControllerDispatcher: This message handler sends the request to an ASP.NET Web API controller.
You can also create your own custom handlers and then add to the Web API pipeline. The Message handlers are good for cross-cutting concerns (such as authentication and authorization) that operate at the level of HTTP messages rather than controller actions. For example, a custom message handler might do the following things
  1. Read or modify the HTTP request headers.
  2. Add a response header to the HTTP response.
  3. Validate the requests before they reach the controller (i.e. Authentication and Authorization).
The following diagram shows two custom handlers (Message Handler1 and Message Handler2) inserted into the Web API pipeline at the Server side.
Server-Side HTTP Message Handlers in WEB API

Creating Custom Server-Side HTTP Message Handlers in Web API
As we already discussed along with the built-in Server-side Message Handlers, you can also create your own Server-Side HTTP Message Handlers. So let’s discuss how to create the Custom Server-Side HTTP Message handlers in ASP.NET Web API.

To create a custom Server-Side HTTP Message Handler in ASP.NET Web API, you need to create a class that must be derived from the System.Net.Http.DelegatingHandler. That custom class then should override the SendAsync method. SendAsync method has the following signature:
Server-Side Message Handlers in WEB API

The SendAsync method takes an HttpRequestMessage as input and asynchronously returns an HttpResponseMessage. A typical implementation does the following:
  1. Process the request message.
  2. Call the base.SendAsync method to send the request to the inner handler.
  3. The inner handler returns a response message. (This step is asynchronous.)
  4. Process the response message and returns the response to the caller.
A sample code is shown below.
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace MessageHandler.Models
{
    public class MessageHandler1 : DelegatingHandler
    {
        protected async override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            Debug.WriteLine("Process request");
            // Call the inner handler.
            var response = await base.SendAsync(request, cancellationToken);
            Debug.WriteLine("Process response");
            return response;
        }
    }
}
Note: The call to the base.SendAsync is asynchronous. If the handler does any work after this call, use the await keyword, as shown in the above example.

A delegating handler can also skip the inner handler and directly create the response. Let’s look at the below example which exactly does the same thing.
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace MessageHandler.Models
{
    public class MessageHandler2 : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Create the response.
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("Hello!")
            };
            // Note: TaskCompletionSource creates a task that does not contain a delegate.
            var tsc = new TaskCompletionSource<HttpResponseMessage>();
            tsc.SetResult(response);   
            return tsc.Task;
        }
    }
}
When a delegate handler creates the response without calling the base.SendAsync method, then the request skips the rest of the pipeline. This can be useful for a handler that validates the request creating an error response. We will discuss this with a complete example in our upcoming article.

How to Add Custom HTTP Message Handlers to the Pipeline in ASP.NET Web API?
To add the Custom HTTP Message Handlers on the server-side, you need to add the Custom Http Message Handlers to the HttpConfiguration.MessageHandlers collection inside the Register method of the WebApiConfig class as shown in the below image:
Server-Side HTTP Message Handlers in WEB API

The Message Handlers are going to call in the same order as they appear in the MessageHandlers collection. The reason is they are nested and the response message travels in the other direction. That is, the last handler is the first one to get the response message.

Notice that you don’t need to set the inner handlers. That is the job of the Web API framework which will automatically connect the inner message handlers.

Now let’s look at some of the examples of custom message handlers.

Example: X-HTTP-Method-Override
The X-HTTP-Method-Override is a non-standard HTTP header. It is basically designed for clients who cannot send certain HTTP request types, such as PUT or DELETE. Instead, the client sends a POST request and sets the X-HTTP-Method-Override header to the desired method type. For example X-HTTP-Method-Override: PUT
So to support this, we need to create a custom message handler that adds support for X-HTTP-Method-Override:
using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace MessageHandler.Models
{
    public class XHTTPMethodOverrideHandler : DelegatingHandler
    {
        readonly string[] _methods = { "DELETE", "HEAD", "PUT" };
        const string _header = "X-HTTP-Method-Override";
        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Check for HTTP POST with the X-HTTP-Method-Override header.
            if (request.Method == HttpMethod.Post && request.Headers.Contains(_header))
            {
                // Check if the header value is in our methods list.
                var method = request.Headers.GetValues(_header).FirstOrDefault();
                if (_methods.Contains(method, StringComparer.InvariantCultureIgnoreCase))
                {
                    // Change the request method.
                    request.Method = new HttpMethod(method);
                }
            }
            return base.SendAsync(request, cancellationToken);
        }
    }
}
Explanation of the above code:
In the above SendAsync method, the handler checks whether the request message is a POST request and whether it contains the X-HTTP-Method-Override header. If so, then it validates the request header value and then modifies the request method. Finally, the handler calls the base.SendAsync to pass the message to the next handler.

When the request reaches the HttpControllerDispatcher class, HttpControllerDispatcher will route the request based on the updated request method.

Example: Adding a Custom Response Header
Let’s see an example of a message handler that adds a custom header to every response message:
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace MessageHandler.Models
{
    public class CustomHeaderHandler : DelegatingHandler
    {
        async protected override Task<HttpResponseMessage> SendAsync(
                HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
            response.Headers.Add("X-Custom-Header", "This is my custom header.");
            return response;
        }
    }
}
In the above example, the handler first calls the base.SendAsync method to pass the request to the inner message handler. The inner handler returns a response message, but it does so asynchronously by using the Task object. The response message is not available until the base.SendAsync completes asynchronously.

Example: Checking for an API Key
Some web services require the clients to include an API key in their request. The following example shows how a message handler can check the requests for a valid API key:
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace MessageHandler.Models
{
    public class ApiKeyHandler : DelegatingHandler
    {
        public string Key { get; set; }
        public ApiKeyHandler(string key)
        {
            this.Key = key;
        }
        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (!ValidateKey(request))
            {
                var response = new HttpResponseMessage(HttpStatusCode.Forbidden);
                var tsc = new TaskCompletionSource<HttpResponseMessage>();
                tsc.SetResult(response);
                return tsc.Task;
            }
            return base.SendAsync(request, cancellationToken);
        }
        private bool ValidateKey(HttpRequestMessage message)
        {
            var query = message.RequestUri.ParseQueryString();
            string key = query["key"];
            return (key == Key);
        }
    }
}
The above message handler looks for the API key in the URI query string. (For the above example, we assume that the key is a static string. A real implementation would probably use more complex validation.) If the query string contains the key, the handler passes the request to the inner handler.

If the request does not have a valid key, the handler creates a response message with status 403, Forbidden. In this case, the handler does not call base.SendAsync, so the inner handler never receives the request, nor does the controller. Therefore, the controller can assume that all incoming requests have a valid API key.

Note: If the API key applies only to certain controller actions, consider using an action filter instead of a message handler. Action filters run after URI routing is performed.

In the next article, I am going to discuss how to implement basic authentication using a message handler in ASP.NET Web API. Here, in this article, I try to explain Server-Side HTTP Message Handlers in WEB API with real-time examples.

Summary:
I hope this post will be helpful to understand the concept of HTTP Message Handlers in WEB API
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts

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...
  • Navigation Menus in ASP.NET Core
    In this article, I am going to discuss how to create Responsive Navigation Menus in ASP.NET Core Application using bootstrap and JQuery. P...
  • 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...
  • Refresh Token in Web API
    In this article, I am going to discuss how to implement Refresh Token in Web API by validating the clients, as well as I, will also discus...
  • HTTP Client Message Handler in Web API
    In this article, I am going to discuss HTTP Client Message Handler in Web API with real-time examples. As we already discussed in HTTP Mes...
  • Anonymous Types in C#
    Hi friends! Today we are going to learn about Anonymous Types in C#. Let's start with the Introduction Anonymous is a type that does...
  • ASP.NET Web API Basic Authentication
    In this article, I am going to discuss how to implement the ASP.NET Web API Basic Authentication step by step with an example. Please read...

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