I am Susil

Invalidating JSON Web Tokens (JWT)

Securing APIs is best practice to protect the integrity of application. JWT authentication has become the standard way for protecting APIs. It is an open standard to pass data between client and server, and enables you to transmit data back and forth between server and consumers in a secure manner.

Asp.Net core provides services to authenticate incoming requests by determining user’s identity. To validate custom logic middleware could be added to pipeline. JWT access token is only valid for a finite period of time. The caveat comes only when you need to invalidate the token based on your business needs. If you need to invalidate a JWT token you will need to wait for the token to expire.

You could store JWT token in database and remove when it needs to be invalidated. This would force the user with valid JWT to login again. Consideration should be done to maintain huge list of user JWT token in datastore and seeking time to locate specific token. There are articles mentioning how to invalidate JWT tokens and this is one which extends to invalidate specific user token with custom logic.

Asp.net core distributed cache supports different datastores to persist information. MySQL is used as datastore in this article, we will need quite a few tools to be installed to create datastore, create cache tables

Entity framework core 

dotnet tool install --global dotnet-ef

Pomelo MySQL tools

dotnet tool install --local Pomelo.Extensions.Caching.MySqlConfig.Tools --version 2.1.0

For this article let consider scenario user log in

        public async Task Login([FromBody] LoginRequest request)
        {
            User user = await userService.AuthenticateUserAsync(request.Email, request.Password);

            if (user == null)
            {
                return Unauthorized();
            }

            string token = GenerateJwtToken(user);

            LoginResponse response = new()
            {
                Id = user.Id,
                UserName = user.Username,
                Token = token
            };

            return Ok(response);
        }

For some purpose admin decides to inactivate users subscription, for clarity purpose the sample prevents user access to website after inactivation. Real scenario will user can login to website but cannot access pages that needs active subscription.

        public async Task DeactivateSubscription(string email)
        {
            User user = await userService.GetUser(email);

            if (user == null)
            {
                return BadRequest();
            }

            await userService.DeactivateSubscription(user);

            await tokenManager.DeactivateCurrentAsync();

            return Accepted();
        }

Deactivation will make an entry to cache table with userid included in the key. If user navigates to another page middleware will be called which would verify if current user has active subscription by checking the database table for any deactivated key. If key is found user will not be allowed to access web page with unauthorized response code.

        public async Task IsActiveAsync(string token)
        {
            string key = GetKey(token);

            string tokenvalue = await cache.GetStringAsync(key);

            return tokenvalue == null;
        }

Conclusion If there are no identity servers available and we are limited to JWT token we could use distributed cache and implement our own logic to invalidate tokens. You could refer the sample code available in Github


Comment Section

Comments are closed.


Migrating charts from HELM v2 to v3 seems to be pretty straight forward for environments having minimal charts and revisions. Consider yourself managing clusters with large volume of deployed applications across multiple environments, here comes migration plan to be prepared and approved.

Backup! Backup!

If you are an ops engineer and before making any changes it is an thumb rule to backup. Backing up HELM charts is pretty easy using Velero tool. Refer commands to backup and restore charts just in case if things goes south. It has cloud including community supported providers to store backup charts.

           velero-backup

Migrate chart

HELM provides an plugin to migrate chart from v2 to v3 named 2to3. Major functionality of the plugin is to convert chart to v3, but has other three required tasks

  • version 2 Configuration migration
  • version 2 Release cleanup
  • Tiller cleanup

            helm-2to3

Migrating to HELM3 involves script changes to your CD pipelines. Release pipelines has reference to tiller namespace, environment will need HELM3 installed with configuration migrated and HELM v3 command mandates namespace while deploying charts to cluster. Synchronization of migrating your charts and updating pipeline stage script is the key. There could be situations if you have migrated the chart and not updated pipeline script, HELM 2 charts will be added after last migration baseline release. Now we can reset baseline again by converting chart to v3 but by skipping releases including previous baseline converted chart.


Comment Section

Comments are closed.


Azure Devops - Deployment Group

I have been using Azure Devops default hosted agent - both cloud and self hosted agents for various personal and org application build and deployments. Recently was tasked migrating custom developed deployment script to Azure Devops. The custom deployment script had lot of intricate steps involving software / application installation and configuration. It was a challenge to accommodate all the steps in release pipelines Agent Job. The worst nightmare is to test if migrated script matches legacy deployment.

Azure Devops pipeline has deployment group - which is a logical set of deployment machines having agents installed in them. This seemed to suit my requirement of executing custom deployment script without much hassle. You could group multiple target machines for an group to deploy and further granular control can be achieved via tags associated with target machine.

You will need to create a deployment group

   

In the next page you will be provided with a registration script that needs to be executed in the target script. Enabled the "Use a personal access token in the script for authentication" checkbox and copy the script.

    

Now login to target machines that will be associated with deployment group. Open powershell (if target machine is windows) in administrator mode and execute the script copied in previous step. Agent will be installed in target machine with the selected option during installation.

Note: If you need to install any module / software make sure you provide local administrator account username and password during registration.

In release pipeline add deployment group job

   

    

If you are using same deployment group to deploy multiple application to various target machine, you could tag each target machine. Select the required tag in deployment group job and deployment will be targetted only to that specific machine.

I had all the infrastructure setup ready and coming to have the actual script i reused existing from repository. Created powershell task and executed function in script witih required parameters. Now that i am reusing tested script from Azure Devops release pipeline i did not worry about rewriting already available code.

    


Comment Section

Comments are closed.


Dotnet core and shared hosting

I have been looking for an blogging application without the need for maintaining database and customized layouts. I created an account in blogspot long back and did not write any useful content. When Scott Hanselman blogged about migrating his website to cloud services from on-premise hosting he mentioned about DasBlog Core. This led me to look into DasBlog Core which is .NetCore migrated version of its original .Net Framework flavor.

Next it was hunting for hosting providers, started researching for providers with arguably minimal pricing and high up time. Narrowed down to Hostinger offering various plans for starters at great deals and had good reviews on their support and panel's ease of use. Went ahead and purchased permium hosting with multiple domains and free domain registration features for four years period. All process was pretty straighforward with option to create SSL using ZeroSSL for additional subdomains. Was excited and deployed my static website - home page. Tada! my website was up and running. 

Now to the interesting part, my blog engine is in .net core and i learnt from hosting provider it was not possible to run .net core application in shared hosting. I did try Hanselman's running .net core on shared hosting linux hosting. As it was highlighted if the application stops it will not try to restart failed application. This was a bummer my plan to have website along with blog was suddenly collapsing. Was looking for any .net core shared hosting provider but to no avail.

Finally had to convert my shared hosting to VPS and with it comes my skills to configure server, since it was mentioned i will have to maintain the server on my own. Installed .net core 3.1, nginx as proxy server and created SSL using Letsencrypt. Steps i followed and issues could be subject another post

   


Comment Section

Comments are closed.


<< Older Posts | Newer Posts >>