Effectively Implemented SingleTon Architecture For REST API

Many Software developers know about the various design patterns.

As per the Software Engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.

Only knowing the design patterns is not enough. But when you are going to think and apply to your solution, then you are on the way to become a Solution Architect.

I have applied one pattern on one of my WCF REST API Service Application. Named as the SingleTon.

I just have limited concepts knowledge of limited Patterns.

One day, I was implementing WCF REST API Service Application for the Mobile Developer.

REST API Service also perform the Authentication. Now this need some clarification.

How to maintain the user credentials and authentication token on the web server?

One possible solution is to create SQL Server Database which stores the credentials information and update accordingly.

But it will decrease the performance of method execution because each time it has to verify the token with SQL Server Database.

One more thing in our project is that, We don’t have any SQL Server database.

So need some different Simple Approach. At that time, I have some little knowledge about SingleTon Pattern. Like,

A Singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance.

Structure :

using System;
public class Singleton
{
   private static Singleton instance;
   private Singleton() {}
   public static Singleton Instance
   {
      get 
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}

If the instance is already created then, it will not allow to create instance and it is also static so we can use that instance at the class level. So If I can store authentication details in that SingleTon instance,then I can also manipulate that instance and maintain authentication information
Now I have tried to associate my authentication requirement to SingleTon Pattern.Anyhow,I need to store authenticated user’s details at the web-server. So I can verify the token.

Now, Its time for implementation,I have created one user credential class

public class UserCredential
{
  public string UserName { get; set; }
  public string Password { get; set; }
  public string Token { get; set; }
  public string Domain { get; set; }
}

And one SingleTon class, which manage the list of UserCredential Information.

public class Singleton
{
  private static Singleton instance;
  public static List<UserCredential> userCredentialList { get; set; }
  private Singleton() { }
  public static Singleton Instance
  {
    get
    {
      if (instance == null)
      {
        instance = new Singleton();
      }
      if (userCredentialList == null)
      {
        userCredentialList = new List<UserCredential>();
      }
      return instance;
    }
  }
  public List<UserCredential> AddCredential(UserCredential userCredential)
  {
    userCredentialList.Add(userCredential);
    return userCredentialList;
  }
}

SingleTon class object, only create one instance of List of User Credentials, and I have to maintain this object using another method called Add Credential, As described above.

So I am not able to create new instance of SinlgeTon, But I can maintain the SingleTon instance with the list of user credentials details. Its static, So it can be accessible by each API method.

For Authentication, and storing the user credential for authenticated user, I have implemented below API method.

public string Authentication(UserCredential userData)
{
  string token = string.Empty;
  AuthenticationResponse authResponse = new AuthenticationResponse();
  try
  {
  if (!string.IsNullOrEmpty(userData.UserName) && !string.IsNullOrEmpty(userData.Password))
  {
    string userName = userData.UserName;
    string password = userData.Password;
    string domain = userData.Domain;
    Singleton singleTon = Singleton.Instance;
    List<UserCredential> existingUserCredentialList = Singleton.userCredentialList;
    int removedUser = existingUserCredentialList.RemoveAll((user) => (user.UserName == userName && user.Domain == domain));

    service = AuthService.ConnectToServiceForAuthentication(userInfo, new TraceListener());
    UserCredential userCredential = new UserCredential();
    if (service != null)
    {
      userCredential.UserName = userName;
      userCredential.Password = password;
      userCredential.Domain = domain;
      userCredential.Token = Guid.NewGuid().ToString();
           singleTon.AddCredential(userCredential);
      token = userCredential.Token;
    }
   }
  }
  catch (Exception ex)
  {
    Logger.Write("Service.Authentication :" + ex.Message + ", " + ex.GetType());
  }
  return token;
}

Above code authenticate the user on Exchange Server. If user is valid, then I store his credentials to the singleton instance with generated token and also return the token for further method calls. So If the user will come again, So he/she has to only need to pass the token. SingleTon instance will only disposed, When we perform the web-server restart or server crash.

At the Web server side, perform the token verification from the above generated singleton instance and return the user credential.

Verification Method :

public static UserCredential VerifyToken(string token)
{
  UserCredential uc = new UserCredential();
  UserCredential userCredential = null;
  try
  {
    Singleton singleTon = Singleton.Instance;
    List<UserCredential> existingUserCredentialList = Singleton.userCredentialList;
    userCredential = existingUserCredentialList.SingleOrDefault((user) => user.Token == token);
  }
  catch (Exception ex)
  {
    Logger.Write("Service.VerifyToken :" + ex.Message + ", " + ex.GetType());
  }
  return userCredential;
}

We can also implement the Log-out method by just removing the user credentials from the SingleTon Instance of List of User Credentials.
We are not dealing with SQL Server Database and we are maintaining the information on the web-server only. So obviously, its faster.

I have just showed the example of just storing the credentials, But you can also think some out of bound scenarios and try to implement it.

Thanks.

Any Suggestions are appreciated.

Advertisements