JWT Authentication for WebAPI

This post is about securing web api using JWT token based authentication. JWT stands for JSON Web Tokens. JSON Web Tokens are an open, industry standard method for representing claims securely between two parties. In token based authentication, the user sends a username and password, and in exchange gets a token that can be used to authenticate requests.

A JWT token look like:

Header.Payload.Signature

HEADER PAYLOAD SIGNATURE
AAAAAAAAAAAAA. BBBBBBBBBBBBBBBBB. CCCCCCCCCCCCC
<base64-encoded header>.<base64-encoded claims>.<base64-encoded signature>

.NET has build in support for JWT tokens in the below namespace.

using System.IdentityModel.Tokens.Jwt;

JWT token has three sections:

  • Header: JSON format which is encoded as a base64
  • Claims: JSON format which is encoded as a base64.
  • Signature: Created and signed based on Header and Claims which is encoded as a base64.

In the below project, we will see how the JWT token authentication has been implemented.

Step 1 – A browser client is going to send a http request with username and password. This is going to be validated using WebAPI filter attribute.

AuthorizationFilterAttribute

Step 2 – Server validates the username and password and completes a handshake. Post handshake, the server generates the token and send it to the client.

The below code is going to generate the token for the user(client)


We need to add below two nuget packages from Nuget Package manager,

Install-Package Microsoft.IdentityModel.Tokens -Version 5.4.0   
Install-Package System.IdentityModel.Tokens.Jwt -Version 5.4.0

Step 3 — Check for token validation

We used System.IdentityModel.Tokens.Jwt library for generating and validating tokens. To implement JWT in Web API, we created a filter for authentication which will be executed before every request. It will verify the token contained in the request header and will deny/allow resource based on token.

Advertisements

C# – why Dictionary is ahead of lists(look ups)

A quick example to demonstrate why the difference between dictionary “look up” versus lists.

The list of list of students and grades in memory, they have StudentId in common.
In a first way I tried to find Grade of a student using LINQ on a list that takes near 7 seconds on my machine and in another way first I converted List into a dictionary then finding grades of the student from the dictionary using a key.

internal class Program
{
    private static void Main(string[] args)
    {
        var stopwatch = new Stopwatch();
        List<Grade> grades = Grade.GetData().ToList();
        List<Student> students = Student.GetStudents().ToList();

        stopwatch.Start();
        foreach (Student student in students)
        {
            student.Grade = grades.Single(x => x.StudentId == student.Id).Value;
        }
        stopwatch.Stop();
        Console.WriteLine("Using list {0}", stopwatch.Elapsed);
        stopwatch.Reset();
        students = Student.GetStudents().ToList();
        stopwatch.Start();
        Dictionary<Guid, string> dic = Grade.GetData().ToDictionary(x => x.StudentId, x => x.Value);
        foreach (Student student in students)
        {
            student.Grade = dic[student.Id];
        }
        stopwatch.Stop();
        Console.WriteLine("Using dictionary {0}", stopwatch.Elapsed);
        Console.ReadKey();
    }
}

public class GuidHelper
{
    public static List<Guid> ListOfIds=new List<Guid>();

    static GuidHelper()
    {
        for (int i = 0; i < 10000; i++)
        {
            ListOfIds.Add(Guid.NewGuid());
        }
    }
}


public class Grade
{
    public Guid StudentId { get; set; }
    public string Value { get; set; }

    public static IEnumerable<Grade> GetData()
    {
        for (int i = 0; i < 10000; i++)
        {
            yield return new Grade
                             {
                                 StudentId = GuidHelper.ListOfIds[i], Value = "Value " + i
                             };
        }
    }
}

public class Student
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Grade { get; set; }

    public static IEnumerable<Student> GetStudents()
    {
        for (int i = 0; i < 10000; i++)
        {
            yield return new Student
                             {
                                 Id = GuidHelper.ListOfIds[i],
                                 Name = "Name " + i
                             };
        }
    }
}

The Magic Console-

Capture1

Make your singleton class thread safe

In this post, we try to get an idea about making thread-safe singleton.

A singleton is a class which only allows a single instance of itself to be created. This class usually gives simple access to that instance. Most commonly, singletons don’t allow any parameters to be specified when creating the instance. Now, in order to make singleton class thread-safe, we can apply to the double-check locking algorithm. In this algorithm, we can put two if conditions to check object is null or not.
First, if condition checks if the object is not null then return the already created object. The second condition we put inside the lock to check if the object is null then only create a new object. The benefit of putting inside condition is to check if multiple threads bypass the first condition at the same time and waiting for their turn to take the lock. Then, in this case, both threads will create a new object. For stopping the above issue, we have to put the second condition.
Below is the example of double-checking locking.
 public class Singleton
    {
        private static readonly Object s_lock = new Object();
        private static Singleton singleton = null;
        private Singleton() { }
        public static Singleton GetSingleton()
        {
            //check 1
            if (singleton != null)
                return singleton; Monitor.Enter(s_lock);
            //check 2
            if (singleton == null)
            {
                Singleton temp = new Singleton();
            }
            Monitor.Exit(s_lock);
            return singleton;
        }
    }