Sunday, July 23, 2023

How to Validate CSRF Tokens in Next.js using NextAuth.js

Introduction

In the world of web development, ensuring the security of user data is of utmost importance. As developers, it is our responsibility to implement measures that protect users from potential attacks. Cross-Site Request Forgery (CSRF) is one such threat that can compromise the integrity of a web application. In this blog post, we will dive into a code snippet that demonstrates how Next.js, in conjunction with the popular authentication library NextAuth.js, handles CSRF protection using NextAuth.js cookies to safeguard user information.

CSRF and Next.js with NextAuth.js

Next.js provides powerful features for building server-side-rendered and statically generated applications. Combining it with NextAuth.js, an authentication library for Next.js, allows developers to easily implement authentication and user sessions with built-in CSRF protection using NextAuth cookies.


Code Walkthrough

  1. The code starts by importing necessary modules, including createHash from the Node.js crypto library and NextApiRequest and NextApiResponse from the Next.js framework.
  2. The exported function takes two parameters: req (NextApiRequest) and res (NextApiResponse), representing the incoming request and the response to be sent back.
  3. The function begins by checking if the request contains a cookie header. Cookies are essential for CSRF protection, as they store the CSRF token required for validation.
  4. If no cookie header is found, the function returns a 403 status code and an error message indicating the absence of cookies.
  5. If cookies are present, the function extracts the raw cookie string from the request header and splits it into an array of individual cookies.
  6. The loop then iterates through the cookie array to find the CSRF token generated by the NextAuth.js library. The NextAuth.js cookies are named next-auth.csrf-token and _Host-next-auth.csrf-token. The _Host- the prefix is used on Vercel to prevent cookie collisions.
  7. Once the CSRF token and hash are obtained, the function proceeds to validate the token against the provided hash.
  8. The valid hash is computed by concatenating the request token with the NEXTAUTH_SECRET, sensitive value stored in the environment variables. The createHash function from the crypto library is used to generate a SHA-256 hash of the concatenated string.
  9. If the computed hash does not match the request hash, it indicates a potential CSRF attack, and the function returns a 403 status code and an error message.
  10. In case of any exceptions or errors during the process, the function catches them and returns a 500 status code with an appropriate error message.

Conclusion

Here we explored a code snippet that demonstrates how Next.js, in collaboration with the NextAuth. authentication library, handles CSRF protection using NextAuth.js cookies to safeguard user data and prevent unauthorized actions. By utilizing NextAuth.js cookies and computing secure hash values, developers can ensure that their Next.js applications remain secure and protected against CSRF attacks.

As developers, it is vital to understand the security mechanisms provided by frameworks and libraries and implement them effectively to build robust and trustworthy web applications. Combining the power of Next.js and NextAuth.js, we can create a seamless and secure user experience for our applications. Happy coding and stay secure!

Sunday, April 12, 2020

Micro Frontends - Part 1: What and Why


“An architectural style where autonomously deliverable frontend applications are created into a more prominent entirety”


Micro Frontends are extensions of microservices architecture and aim to apply the same principle to the frontends.
           
In the early days of software development, both the frontend and backend components would be bundled into one application which we now call it as a monolith style of application. Physically this type of application can live in one code repository. And that code repository would contain directories for frontend and backend part of the application but it was a one large solution which contained UI and business logic which would be maintained by one large team.as the Monolith are huge, changing anything would be taken seriously as testing and deployment was a huge task as the impact of breaking anything else that was unrelated to the change.

Frontend and Backend: The industry soon realised the advantage of breaking the frontend and backend and at the same time we ended with separate teams that specializes in backend development and front end development. Things generally improved with the split but the backend teams started to suffer with scaling issues as the business logic , functionality and data grew so did the size of the BE. so when we started to realize that one backend system in the form of API and services had to serve multiple different types of frontend in the form of mobile application and web applications something had to be done to address these issues. 


So the solution of the backend system was to use microservices architecture to split the large monolith applications into smaller services and api’s each with the clear scope and responsibilities. And each microservice had a dedicated team that specializes within that services responsibility in terms of domain knowledge. And the frontend team would call different api’s for the different part of the frontend application and this would have been done via API gateway or a backend for frontend(BFF) API which would talk to other downstream microservices

So in last few years we realized that microservices at the backend resolved these scaling issue and now we have issues at the frontend side of the application
                       
Microservices design principles (same can be incorporable for frontend)
  1. High Cohesion - each microservice has on responsibility and focus . I does one thing and does well
  2. Autonomous - Each MS can be independently changed and deployed
  3. Business domain centric - MS has one single focus but also represents specific business domain or function within the organisation
  4. Resiliency - even when there is failure, the system is resilient failure. It tries to fail fast and embrace the failure by defaulting or degrading the functionality
  5. Observable - Using centralized logging and monitoring see what each component is doing.. Also monitor the health
  6. Automation - automate using the tools for independant testing and deploying


Problems with Monolith Frontends:
  1. Scaling issues - with the architecture and the teams, the codebase has gone so large and intertwined so making small changes takes longer. Instead of scaling one part of the application you end up scaling the entire monolith. Also needs large team to maintain the application which means a small change needs a lot of coordination
  2. Communication issues between large frontend team and backend teams for simple ui change as  the priorities of the teams will be different
  1. Code and testing complexity can increase the risk of managing the monolith applications
  2. Slow continuous delivery
           
Advantage of Monolith frontends:
1.     Single code base
2.     Easier to setup for testing and development purposes

As the monolith frontend codebase grows over time:

What Increases:
1.     Dependencies - FE dependencies on internal and external 3rd party libraries/components grows which also increases the overall complexity
2.     Team size:  to maintain the growing and complex code base the team size increase
3.     Coordination: as the size of the team increases, the coordination required to make a small change increases

What Decreases:
1.     Ability to Change : ability for adapting a change slows due to the coordination effort required, also the technology used in frontend becomes older and more stale as the project ages.
2.     Staff availability: As the tech stack and tech choices become stale, the availability of staff with a specific skill in the market also decreases.
3.     Innovation and releases


The above problems can be described with a graph of “Law of Diminishing Returns”

 

Micro Frontend to the rescue


The approach is quite similar to BE, we take our large application and split it into a smaller components, however there is a lot more for Micro Frontends approach than just splitting. We try to make our software vertically sliced end to end, which means our micro frontends are inline with supporting backend micro services. Each vertical slice is basically a end 2 end feature.


For example: 
Within your web app, you have a cart section which is an end to end feature in the form of a micro frontend which is a cart section and in the backend it has a microservice or number of micro services which support that micro frontend and this entire feature is owned by one team which supports, maintains and develops this feature end to end which includes micro frontend also the supporting microservices in the background and any storage associated with each one of those services. 

This type of vertical slicing and team ownership of end to end feature means we inherit now the benefits of microservices and we can now independently change, deploy feature end to end without affecting the rest of our application. If we have specific performance issues we can focus on scaling out that aspect of our application. We also now have the clear end to end ownership of the features within our applications. Also the team has the domain knowledge as they own the complete feature.

One of the key aspect of the Microservice architecture is to give the illusion of one unified application and not to give away the fact that the application is actually made up of multiple micro frontends. The most common scenarios to achieve this is to use a base app which is basically a shell housing our micro frontends. So the base app or shell or browser they interact with each other giving the user an illusion of one functioning application that's consistent and coherent.

In the next article we would be talking about Micro Frontend Design Principles.



Thursday, June 23, 2011

Firefox 5 Released, is it better?

New privacy settingsMozilla has released Firefox 5, Sticking to its promise of a quick-release cycle, just three months after Firefox 4 made its debut in March.

According to Mozilla foundation, the Firefox 5 includes more than 1,000 improvements and performance enhancements that make it easier to discover and use all of the innovative features in Firefox. 



So here it is what it has in store:

Firefox 5 allows mobile users to tweak their privacy settings directly from their mobile devices. The settings page is laid out in a way that a user can exactly see which options are on and which are off.

One of the major changes is the ability to enable the Do Not Track feature. This is a feature being used by several new versions of browsers today. It lets you tell a site that you want to opt-out of third-party tracking for behavioral advertising. In Firefox 4 this feature was buried deep in the options -- Options >> Advanced >> General and under Browsing you'd check the option: Tell web sites I do not want to be tracked. Now you just need to go into Firefox Options >> Privacy and under Tracking, check Tell web sites I do not want to be tracked.

Most enhancements and improvements claimed by Mozilla seem to be minor bug fixes according to reviewers. Some significant changes include enhanced support for HTML5 and new support for CSS (cascading style sheet) animations. Firefox 5's user interface is quite similar to Firefox 4.

Some other changes in Firefox 5 are said to include better spell checking in some languages; improved JavaScript, memory and networking performance. 

Firefox 5 offers better Linux desktop integration and improved background tab performance.

Also on-board Firefox 5: The ability to play CSS animations, and the capability to instantly tinker with Firefox add-ons, without slowing down the show or shutting off the browser. 

Mozilla also insures that it can respond quickly to complaints from users, and more easily transform the browser experience to meet consumer need.