In web application, Security is essential. User wants to use resources of our system. For that, we need to authenticate user. Authentication means need to check whether user is eligible to use system or not. Generally, we do authentication via username (in form of unique user name or email id) and password. If user is authenticated successfully, then we allow that user to use resources of a system. But what about subsequent requests? If user has been already identified then s/he does not need to provide credentials each time. Once authenticated, for particular period s/he can use system’s resources. In traditional approach, we used to save Username in Session. This session period is configurable it means session is valid for 15 minutes or 20 minutes. This session is stored in server’s memory. After expiry of session, user needs to login again.
But here, there are couple of problems.
- Session can be high jacked.
- If we have multiple instances of server with load balancer then if request goes to server other than the server which has authenticated the earlier request, then it will invalidate that session. Because session is not distributed among all the servers. Here, we have to use Sticky session that is we need to send each subsequent request to same server only. Here, we can also store session in database instead of server’s memory but in that case, each time we need to query database and that’s extra network call which may increase overall latency.
To solve this problem, we can do authentication via JWT i.e. Json web token. After successful authentication, server will generate security token and send back to client. This token can be generated using Symmetric key algorithm or Asymmetric key algorithm. On each subsequent request after successful login, client will send generated token back to server. Server will check whether sent token is valid or not and also checks whether its expired or not. Client will send this token in Authentication Bearer header.
JWT token has particular format. Header, Payload and Signature.
- Header: We need to specify which token system we want to use and also need to specify algorithm type.
- Payload: This is token body. Basically, it contains expiry detail, claims details, issuer detail etc.
- Signature: To create the signature part we have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.
E.g. HMACSHA256( base64UrlEncode(header) + “.” + base64UrlEncode(payload), secret)
Benefits of using JWT:
- JSON parser are common in programming languages.
- Secure. We can use Symmetric or Asymmetric key algorithm.
- Less verbose in compare to SAML.
I have created ASP.Net Core web API sample application. JWTAuthService is responsible for generation and validation of token. Feel free to download / contribute code on Github.