Consume Refresh Token in C# Client

Consume Refresh Token in C#

In this article, I will discuss how to Consume Refresh Token in C# application. Please read the following three articles, before proceeding to this article as we are going to consume the services that we created in our previous 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.

Generating Refresh Token in Web API: In this article, we discussed how to Generate Refresh Token in Web API.

Let us discuss the step by step procedure to Consume Refresh Token in C#. But before that let’s modify the Test Controller of our Web API application that we created in our previous application as shown below.

Step1: Modifying the Test Controller
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()));
        }
    }
}
Step2: Creating the UserTokenMaster table

In the client side, we need to store the token in the UserTokenMaster table as shown below

Consume Refresh Token in C#

Please use the below SQL Script to create the required database.

CREATE DATABASE Test_DB
GO

USE Test_DB

CREATE TABLE UserTokenMaster
(
  UserName VARCHAR(50) PRIMARY KEY,
  UserPassword VARCHAR(50),
  AccessToken VARCHAR(500),
  RefreshToken VARCHAR(100),
  TokenExpiredTime DATETIME
)
GO

Step3: Create a new console application with the name RefreshTokenClient1.

Step4: Add ADO.NET Entity Data Model

Here, we need to add ADO.NET Entity Data Model Database First approach against the Test_DB and add the UserTokenMaster to the EDMX that we created in Step2. So once you add the table, the EDMX File should be as shown below

Consume Refresh Token in C#

Step5: Add Token class

Now we need to add a class file with the name Token to the project. And then copy and paste the following code.

using Newtonsoft.Json;
using System;
namespace RefreshTokenClient1
{
    // The body of the response from API is a JSON object that 
    // contains the following properties (and a couple of others
    // that we're not capturing).
    public class Token
    {
        [JsonProperty("access_token")]
        public string AccessToken { get; set; }

        [JsonProperty("token_type")]
        public string TokenType { get; set; }

        [JsonProperty("expires_in")]
        public int ExpiresIn { get; set; }

        [JsonProperty("refresh_token")]
        public string RefreshToken { get; set; }
        
        public string Error { get; set; }

        public DateTime ExpiredDateTime { get; set; }
    }
}
Step6: Adding UserTokenRepository

Now we need to add a class with the name UserTokenRepository and within that class we are going to perform the database operations. So once you add the class, copy and paste the following code.

using System;
using System.Linq;

namespace RefreshTokenClient1
{
    class UserTokenRepository : IDisposable
    {
        // Test_DBEntities it is your context class
        Test_DBEntities context = new Test_DBEntities();

        public Token GetTokenFromDB(string username, string password)
        {
            UserTokenMaster userMaster = context.UserTokenMasters.FirstOrDefault(user =>
            user.UserName.Equals(username, StringComparison.OrdinalIgnoreCase)
            && user.UserPassword == password);
            Token token = null;

            if (userMaster != null)
            {
                token = new Token()
                {
                    AccessToken = userMaster.AccessToken,
                    RefreshToken = userMaster.RefreshToken,
                    ExpiredDateTime = (DateTime)userMaster.TokenExpiredTime
                };
            }

            return token;
        }

        //Adding Token into the DB
        public bool AddUserTokenIntoDB(UserTokenMaster userTokenMaster)
        {
            //First Check the existance of the Token in the DB
            var tokenMaster = context.UserTokenMasters.FirstOrDefault(x => x.UserName == userTokenMaster.UserName
                            && x.UserPassword == userTokenMaster.UserPassword);
            if (tokenMaster != null)
            {
                context.UserTokenMasters.Remove(tokenMaster);
            }

            context.UserTokenMasters.Add(userTokenMaster);

            bool isAdded = context.SaveChanges() > 0;
            return isAdded;
        }
        
        public void Dispose()
        {
            context.Dispose();
        }
    }
}
Step7: Modify the Program class

Here we need to implement the logic to get the access token and refresh from token API and then storing the Token into our database. The following code is self-explained, please go through the comments.

That’s it. Run the application and see everything is working as expected. In the next article, I will discuss how to consume Refresh Token using JavaScript.

SUMMARY
In this article, I try to explain how to implement Consume Refresh Token in C# 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.

Leave a Reply

Your email address will not be published. Required fields are marked *