Authentication is one of the most important parts of any web application. Cookies and server-based authentication were the easiest solution then then. However, handling authentication in modern Mobile and Single Page Applications can be tricky, and demand a better approach. The best known solutions today for authentication problems for APIs are the OAuth 2.0 and the JSON Web Token (JWT).
Before we can look at why JSON web Token has taken over cookies its important to know what really the two really work.
A cookie is a small piece of data sent from a website and stored in the user’s web browser while the user is still browsing it, so that every time the user loads the website, the browser sends the cookie back to the server to notify the user’s previous activity If the request is valid therefore creating a session by using the user information fetched from the database, and then returning the session information in the response header in order to store the session ID in the browser. for example When you enter your email and password into the Facebook login page, you get into your account. Then, wherever you go in the site, you always see your photo at the top right corner of the page. Facebook remembers you and doesn’t ask for the password again and again. This works thanks to HTTP cookies called cookie-based authentication.
Here is a step by step of how cookies work:
1.Step one: The user enters a username and password and clicks “submit”. The server receives a POST request with information inside:
POST / HTTP/1.1 Host: www.facebook.com Content-Type: application/x-www-form-urlencoded firstname.lastname@example.org&password=itsruddy
The server matches information the provided with its records and decides what to do. If information(username&password) is invalid,it returns the same login page asking you to enter it all again but if the information(username&password) is valid the server returns something like this:
HTTP/1.1 303 See Other Location: www.facebook.com Set-Cookie: email@example.com
Since the response status code is 303, the browser goes to the page specified in the Location header and opens the front page of the site. This is what it sends to the server:
GET / HTTP/1.1 Host: www.facebook.com Cookie: firstname.lastname@example.org
The server gets my email from the Cookie header and understands that it’s me again hence there is no need for my password once more. The server trusts the information from the Cookie and that is what Cookie-based authentication is all about.
The main reason as to why it made sense to try a different approach other than cookies is on Security because if the server trusts any browser request with a user email in the Cookie header, anyone(malicious hacker) would be able to send a another user’s email from another place and get access to the other user’s account. read here on how to encrypt the email with a secret encryption key in cookies.
A token-based authentication system allows the user to enter a username and password in order to obtain a token which allows them to fetch a specific resource without using their username and password. Once the token has been obtained,the user can offer the token which offers access to a specific resource for a time period to the remote site.
Here is a step by step of how Token-Based Authentication works:
1. The user provides a username and password in the login form and clicks log in.
2. After a request is made, the application validates the user’s credentials(username & password) on the backend by querying in the database. If the request is valid, a token is created by using the user information fetched from the database, and then returns that information in the response header so that the token can be stored in local storage.
3. The application provides token information in every request header for accessing restricted endpoints in the application.
4. If the token fetched from the request header information is valid,it lets the user access the specified end point,and respond with JSON or XML.
The Benefits of tokens are
Stateless and Scalable
Tokens stored on client side are completely stateless,and ready to be scaled because the loader balancers in our application are able to pass along to any server since there is no state or session information anywhere.If we were to keep session information on a user that was logged in,this would require us to keep sending that user to the same server that they logged in at called session affinity.
These problems are gone with tokens since the token itself holds the data for the user.
The Token is sent on every request and since there is no cookie being sent, this helps to prevent CSRF attacks. Even if your specific implementation stores the token within a cookie on the client side, the cookie is merely a storage mechanism instead of an authentication one. There is no session based information to manipulate since we don’t have a session!
The token expires after a set amount of time, so a user will be required to login once again. This helps us to stay secure,as there is also the concept of token revocation that allows us to invalidate a specific token and even a group of tokens based on the same authorization grant.
Tokens will allow us to build applications that share permissions with another. For example, we have linked random social accounts to or major ones like Facebook or Twitter. When we log to Twitter through a service(let’s say buffer), we are allowing buffer to post to our twitter stream. By using tokens, this is how we provide selective permissions to their party applications. We could also build our API and hand out special permission tokens if our users wanted to give access to their data to another application.
Multiple Platforms and Domains
As we expand our application we will need to provide access to all sorts of devices and applications since our application becomes popular. Since our API just serves data we can also make the design choice to serve from CDN that’s why don’t have to worry about cross-origin resource sharing(CORS) because the CDN design eliminates the issues of cross-origin resource sharing after we set a quick header configuration for our application.
Problem with server based authentication
Every time a user is authenticated,the server will need to create a record somewhere on our server. This is usually done to create a record somewhere on our server usually done in memory and when there are many users authenticating,the overhead on your server increases.
Sessions are stored in memory which provides problems with scalability. AS our cloud providers start replicating servers to handle application load,having vital information in Session memory will limit our ability to scale.
Cross-Origin Resource Sharing(CORS)
As we expand our application to let our data be used across multiple mobile devices,we have to worry about Cross-origin resource sharing(CORS).When using AJAX calls to grab resources from another domain(mobile to our API server), we could run into problems with forbidden requests.
Cross-Site Request Forgery(CSRF)
Users are susceptible to CSRF attacks since they can already be authenticated with say a banking site and this could be taken advanted of when visiting other sites. With these problems scalability being the main one,it made sense to try a different approach.
Posted by Rufus Nganga