Wednesday 22 January 2020

Basic Introduction to JSON Web Token(JWT)

In this article, you will learn the basic fundamental of JWT like how it works, what is JWT, what is the structure of JWT. If you would like to implement JWT based authentication in your API, you can either use one of the existing open source libraries JWT.io available for various programming languages or you can find several other libraries for .NET, Python, Java, etc.

How JWT works?

The reason behind JWT popularity is that it ensures you, the sent data is actually created from an authentic source. When a user sends a request to the server with a valid credential. A JSON Web Token will be returned back to the user from the server. A user has to send again request to the server with the received JWT, typically in the Authorization header using the Bearer schema. The server will check for a valid JWT in the Authorization header received from the user request, and if it’s present, the user will be allowed to access protected resources.
You can see in the below diagram that all work carried out using four steps only.
[su_box title=”Note :” box_color=”#faf62b” title_color=”#151111″]Tokens are secret credentials, so you must have to take great care to prevent security issues. Generally, you should not keep tokens longer than it is required.[/su_box]

What is JWT ?

  • JWT stand for JSON Web Token.
  • It is an open standard. Open standard means anybody can use it.
  • It securely transfers information between any two servers.
  • It is digitally signed. Digitally signed means it is verified and trusted. There is no alteration of data while transfer.
  • It can be signed using a secret (with the HMAC algorithm) or a public/private key pair by using RSA or ECDSA(Elliptic Curve Digital Signature Algorithm) encryption.
  • It is highly compact. JWT is used to send via URL using POSt request and HTTP Header.
  • It provides a fast transmission of data.
If you are interested to read more about RSA or ECDSA encryption technique, you can navigate below the article.
https://simple.wikipedia.org/wiki/RSA_algorithm
https://en.wikipedia.org/wiki/RSA_(cryptosystem)

What is the structure of JWT ?

JWT is basically a string text containing three different parts separated by dot(.) Three different parts are
  • Header
  • Payload
  • Signature
[su_note note_color=”#fdf6d5″]header.payload.signature[/su_note]
Let’s go through each one, starting with the header.
Header – This is the first separated part of JSON Web Token which basically Identifies which algorithm is used to generate the signature like MAC SHA256 or RSA.
Example – [su_note note_color=”#fdf6d5″]
{
“alg” : “HS256”,
“typ” : “JWT”
}
[/su_note]
In this JSON, You can see the value of the typ key specifies that the object is a JWT, and the value of the “alg key specifies which hashing algorithm is being used to create the JWT signature component. In our example, we are using the SHA256 algorithm, a one way hashing algorithm that uses a secret key in order to compute the signature
Payload – This is the second separated part of JSON Web Token which basically contains the claims.
Claims are the statements about the entity, such as a user. And also, the payload contains the additional metadata. There are three types of Claims: Registered, Public, and Private.
Registered claims are set of the predefined claims which is mainly recommended but that are not eventually mandatory. Here, the claim names are three characters long, so JWT can be as compact as possible. In our article we have used registered claims.
Public claims are claims that can be defined at your “own will” just to avoid the collisions, which means there is no any restriction has been set. claims should be defined in Internet Assigned Numbes Authority (IANA ) Json.
Private claims are the custom claims that are mainly created to share the information between user and server.
Example – [su_note note_color=”#fdf6d5″]
{
“sub”: “13254789”,
“name”: “code-adda”,
“iat”: 1516239022
}
[/su_note]
You can put as many claims as you like. These fields can be useful when creating JWT, but they are optional.
Have a look at the wikipedia page on JWT for getting a more detailed list of JWT standard fields.
[su_box title=”Note :” box_color=”#faf62b” title_color=”#151111″]Never put any important and secure information in the Payload because an attacker can access it.[/su_box]
Signature – This is third and last separated part of JSON Web Token which basically securely validates the token. The signature is used to verify that the message wasn’t changed in transition. To create a signature you have to take the encoded header and the encoded payload, a secret(the algorithm specified in the header), and sign that.
Example – [su_note note_color=”#fdf6d5″]
HMACSHA256(
base64UrlEncode(header) + “.” +
base64UrlEncode(payload),
your-256-bit-secret
)[/su_note]
[su_box title=”Note :” box_color=”#faf62b” title_color=”#151111″]The resulting string(encoded header and the encoded payload) is concatenated with a period(.) separator, and then run through the cryptographic algorithm specified in the header, in this example we are using HMAC-SHA256.[/su_box]

Generating JWT token

We have already created all the three components, now we are ready to create the JWT. Remember the header.payload.signature structure of the JWT, we simply need to combine the components, with periods (.) separating them. We use the base64url encoded versions of the header, payload, and the signature. See in below picture how newly created JWT look like. For better readability, I’ve colored each part of three components, header-payload-signature.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMzI1NDc2OTgiLCJuYW1lIjoiY29kZS1hZGRhIiwiaWF0IjoxNTE2MjM5MDIyfQ.BxQwOgdPMq440l6Z0YdAPmveK2kF7ZM4oaPfWnQq93U
You can try creating your own JWT through your browser at jwt.io.

How to use JWT Token?

While authentication, just after the user successfully send a request to the server with their valid credentials, a JSON Web Token will be returned. The tokens are a way to authenticate the request. Now the token is always to be sent with request typically in the Authorization header using the Bearer schema. Please note down how to send a request with JWT received token.
[su_note note_color=”#fdf6d5″]Authorization: Bearer <>
Example – Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMzI1NDc2OTgiLCJuYW1lIjoiY29kZS1hZGRhIiwiaWF0IjoxNTE2MjM5MDIyfQ.BxQwOgdPMq440l6Z0YdAPmveK2kF7ZM4oaPfWnQq93U[/su_note]
It’s not over yet, I hope at the end of this article you have a basic understanding of JWT and the way it actually works. In the next article, we will have another article for you to implement JSON WEB TOKEN for securing ASP.Net WEB API. Till then keep learning. ðŸ™‚

How to secure ASP.NET Web API using basic authentication

secure ASP.NET Web API using basic authentication
ASP.NET Web API allows us different ways to implement security while exposing resources. In the previous article, we have learned about how to secure ASP.NET WEB API using token-based authentication. In this article, we are going to learn how to secure ASP.NET WEB API using basic authentication. Basic Authentication is easy to implement, expose and consume and is widely supported by any Web client, but it’s not as secure as token-based authentication and it requires that SSL(Secure Sockets Layer) is used to keep the encoded credentials in order to the safe application from simple attacks.
Implementation of ASP.NET Web API using basic authentication
Step 1 :
create a class for your filter and inherit it with AuthorizationFilter. Here, we are going to create Inherit “BasicAuthenticationAttribute” class from “AuthorizationFilterAttribute” class which reside in “System.Web.Http.Filters” namespace. Inside “BasicAuthenticationAttribute” class we will override OnAuthorization function of “AuthorizationFilterAttribute”
Here, we are using Base64 format to encrypt the username:password. Once you get the value from the header, it converts to original value which only contains the username and the password. Format used to store username and password is “username:password
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = actionContext.Request
.CreateResponse(HttpStatusCode.Unauthorized);
}
else
{
string authToken = actionContext.Request.Headers
.Authorization.Parameter;
string decodedAuthToken = Encoding.UTF8.GetString(
Convert.FromBase64String(authToken));
string[] unamepwdVal = decodedAuthToken.Split(':');
string username = unamepwdVal[0];
string password = unamepwdVal[1];
if (LoginPolicy.Validate(username, password))
{
Thread.CurrentPrincipal = new GenericPrincipal(
new GenericIdentity(username), null);
}
else
{
actionContext.Response = actionContext.Request
.CreateResponse(HttpStatusCode.Unauthorized);
}
}
}
}
Step 2 :
We are going to add a class LoginPolicy and have a function Validate containing two parameters “username” and “password” to validate authentication while consuming resources.
public class LoginPolicy
{
public static bool Validate(string username, string password)
{
// you can read username and password value from database and can easly use here to validate.
if (username.Equals("user@abc", StringComparison.OrdinalIgnoreCase) &amp;&amp; password == "user@123")
{
return true;
}
else
{
return false;
}
}
}
view rawloginpolicy.cs hosted with ❤ by GitHub
Step 3 :
We have created our basic authorization filter and now its time to implement it in your controller. You just have to register it. Here we are going to create controller name “TestController” and implement “BasicAuthentication” on action level.
[BasicAuthentication]
public HttpResponseMessage Get()
{
string username = Thread.CurrentPrincipal.Identity.Name;
DataSet dsRecord = new DataSet();
if (username == "user@abc")
{
return Request.CreateResponse(HttpStatusCode.OK,
"Hello Learner.. Thanks for learning at code-adda.com");
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
Great.. Now you have successfully created your WEB API using basic authentication. You can use WEB API testing tools like fiddler or postman. Don’t worry we will guide you how to check. In last article – How to secure ASP.NET Web API using Token Based Authentication we learnt how to test Web API using postman, Here we are going to learn how to consume WEB API using fiddler. Follow given steps.
  • Select action type – GET
  • Enter WEB API link
  • Enter Header value.
[su_note]Host: localhost:63938 Authorization : Basic dXNlckBhYmM6dXNlckAxMjM=[/su_note]
  • Select protocol type.
  • Click on execute button.
You can see the response when you click on the execute button. Have a look at below pic.
How to secure ASP.NET Web API using basic authentication
You can download complete source code from here
[su_button url=”https://github.com/code-adda” target=”blank” style=”3d” background=”#7a1d18″ size=”5″ radius=”round”]Download Source Code [/su_button]

Baisic Useful Git Commands

  Pushing a fresh repository Create a fresh repository(Any cloud repository). Open terminal (for mac ) and command (windows) and type the be...