Web API Authentication with JSON Web Token:

The latest approach in authenticating a user is through token based authentication. One of the most famous and reliable token based approach is the JSON based Open standard, also known as the JSON Web Token (JWT). JWT basically consists of 3 parts –

  • Verify Signature: This is signed and created based on claims and headers encoded as base64.
  • Payload: JSON formatted data encoded as base64.
  • Header: JSON formatted data encoded as base64.

To verify if the request coming from to our API is a valid source, we use JSON Web token. The JWT has the capability to encode enormous amounts of sensitive data and is very light-weight. The JSON web token can even be passed as query string.

How to create a JSON Web Token(JWT):

  • Use System.IdentityModel.Tokens.jwt namespace available in the NuGet package and generate the token.
  • Validate a user in the database and see if it is successfully validated. If yes, then generate a token by applying its information in Payload. Return the token back to the user.
  • Write the below method after creating a .cs file

private

const string Secret = “db3OIsj+BXE9NZDy0t8W3TcNekrF+2d/1sFnWG4HnV8TZY30iTOdtVWJG8abWvB1GlOgJuQZdcF2Luqm/hccMw==”;

public static string GenerateToken(string username, int expireMinutes = 20) {

var symmetricKey = Convert.FromBase64String(Secret);

var tokenHandler = new JwtSecurityTokenHandler();

var now = DateTime.UtcNow;

var tokenDescriptor = new SecurityTokenDescriptor {

Subject = new ClaimsIdentity(new [] {

new Claim(ClaimTypes.Name, username)

}),

Expires = now.AddMinutes(Convert.ToInt32(expireMinutes)),

SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature)

};

var stoken = tokenHandler.CreateToken(tokenDescriptor);

var token = tokenHandler.WriteToken(stoken);

return token;

}

  • The returned token is either saved in cookies, local storage or a session. The reason being, for every new request, this token must be attached in the header for validation. This way, the API ensures that the request coming is from a valid user.

How to consume JSON Web Token(JWT):

In the WebpiConfigFile, add AuthorizationAttribute.

For instance, config.Filters.Add(new AuthorizeAttribute());

The jwtAuthenticationAttribute inherits from IauthenticationFilter. With this attribute, any action can be authenticated by putting that attribute in the action.

public class ValueController: ApiController {

[JwtAuthentication]

public string Get() {

return “value”;

}

}

The authentication filter core method is as below:

private static bool ValidateToken(string token, out string username) {

username = null;

var simplePrinciple = JwtManager.GetPrincipal(token);

var identity = simplePrinciple.Identity as ClaimsIdentity;

if (identity == nullreturn false;

if (!identity.IsAuthenticated) return false;

var usernameClaim = identity.FindFirst(ClaimTypes.Name);

username = usernameClaim ? .Value;

if (string.IsNullOrEmpty(username)) return false;

// More validate to check whether username exists in system

return true;

}

protected Task < IPrincipal > AuthenticateJwtToken(string token) {

string username;

if (ValidateToken(token, out username)) {

// based on username to get more information from database in order to build local identity

var claims = new List < Claim > {

new Claim(ClaimTypes.Name, username)

// Add more claims if needed: Roles, …

};

var identity = new ClaimsIdentity(claims, “Jwt”);

IPrincipal user = new ClaimsPrincipal(identity);

return Task.FromResult(user);

}

return Task.FromResult < IPrincipal > (null);

}

Below is the code to validate JWT token and get the Principal back:

public static ClaimsPrincipal GetPrincipal(string token) {

try {

var tokenHandler = new JwtSecurityTokenHandler();

var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;

if (jwtToken == nullreturn null;

var symmetricKey = Convert.FromBase64String(Secret);

var validationParameters = new TokenValidationParameters() {

RequireExpirationTime = true,

ValidateIssuer = false,

ValidateAudience = false,

IssuerSigningKey = new SymmetricSecurityKey(symmetricKey)

};

SecurityToken securityToken;

var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken);

return principal;

catch (Exception) {

//should write log

return null;

}

}

Thus, the principal is returned and JWT token is validated. To check the role authorization, you must build a new local identity and insert more information.

AJ for Smart IMS

FacebookLinkedInInstagramTwitter

About Smart IMS – ConnX

Smart IMS – ConnX is a technology solutions oriented company integrating Application Development, Cloud Transformation Services, Managed Services and Professional Services.

As a leader in the unified communications field, Smart IMS – ConnX consistently delivers applications to enable users to be mobile, agile and competitive, helping enterprises to increase revenues, improve efficiency and mitigate risks.

The company, headquartered in Plainsboro, New Jersey (US), with offices in India, Singapore, Sydney, deploys a global delivery model and deep domain expertise originating in the Trader Voice and Financial sector, with a focus on transforming traditional PBX to SIP-based telecommunications services.

Smart IMS serves Fortune 1000 as well as emerging organizations across industries and geographies to transform their business from traditional model to cloud and digital.
Our values and culture is focused to deliver quality, scalability, predictability in execution and an enhanced customer experience.

For more information, visit…

SmartIMS.com
ConnXai.com

Please follow and like us: