Securing Node.js APIs with Decentralised Identity Tokens

Rate this content
Bookmark

Authentication and Authorization are serious problems. We often dedicate a lot of time to craft powerful APIs but overlook proper security measures. Let's solve it with Magic using a key-based identity solution built on top of DID standard, where users’ identities are self-sovereign leveraging blockchain public-private key pairs. In this talk, we’ll look at proper ways to secure our Node.js APIs with Decentralised Identity Tokens. We’ll go from learning what Decentralised Identity standards are, how the users’ identities are self-sovereign leveraging blockchain public-private key pairs, why they’re the future of API security, and to put theory into practice we will build a real-world implementation using Node.js where I’ll show common best practices.

This talk has been presented at JSNation Live 2021, check out the latest edition of this JavaScript Conference.

FAQ

A decentralized identity token (DID) is a digital identity token that leverages blockchain technology and elliptic curve cryptography to provide verifiable proof of authentication and authorization. It consists of a proof and a claim, where the claim includes the user's data and the proof is generated using Ethereum's personal sign algorithm and the user's private key.

A DID token is generated by encoding a Base64 string, JSON string tuple representing proof and claim. The claim contains the user's public key and other data, and the proof is created by signing the claim using Ethereum's personal sign algorithm and the user's private key. The token is then encoded for secure HTTP transport.

By default, a DID token generated using Magic has a lifespan of 15 minutes. However, this duration can be extended by calling the getIDtoken function.

To secure a Node.js API using Magic, start by setting up your API with the Magic SDK. Use the 'login with email' function to authenticate users and issue DID tokens. Protect API routes by incorporating middleware that validates these tokens, allowing only authenticated requests to access protected resources.

To begin building a Node.js API with Magic, run the command 'npx makemagic', select the 'express API' template, and follow the prompts to configure your application. You'll need to provide an application name and your Magic secret key, which you can obtain from the Magic dashboard.

In Magic, the publishable key is intended for use in client-side applications, allowing them to interact with Magic's services without exposing sensitive operations. The secret key, on the other hand, is used on the server side for operations that require higher security, such as token validation and user session management.

To validate a DID token in a Node.js middleware function, first check if the authorization header is defined. Extract the DID token from the header, then use the Magic SDK's token.validate() function to confirm its validity. If the token is valid, proceed with the next middleware function; otherwise, handle the error accordingly.

Mohammad Shahbaz Alam
Mohammad Shahbaz Alam
9 min
11 Jun, 2021

Comments

Sign in or register to post your comment.
Video Summary and Transcription
This talk introduces the concept of securing a Node.js API using a decentralized identity token. The token is encoded as a Base64 string and consists of a proof and claim. The API is built using Express and protected using Magic. The application has multiple routes, with the secret route being protected by middleware. The authorization header is checked and the DID token is validated for access to protected routes.

1. Introduction to Decentralized Identity Token

Short description:

Welcome to this talk about securing a Node.js API using a decentralized identity token. We will learn what a decentralized identity token is, build a Node API using Express, and protect it using Magic. DID token is encoded as a Base64 string, JSON string tuple, leveraging Ethereum blockchain algorithm and elliptic curve cryptography. It consists of proof and claim, with claim representing the user's data and proof being signed using Ethereum's personal sign algorithm. The easiest way to get started with Magic is using the client SDK and calling the login with email function. Let's build the API by running npx makemagic select the template express API.

Welcome to this talk, where we will learn more about securing a Node.js API using a decentralized identity token. My name is Mohamed Shabaz Alam, a developer advocate at Magic.

In this talk, we will learn what is a decentralized identity token, build a Node API using Express, and then protect that API using Magic.

So what is DID token? DID token created by Magic is adapted by prior tech like JWTs and W3 DID protocol. It is encoded as a Base64 string, JSON string tuple, which is representing proof and claim. It leverages the Ethereum blockchain algorithm and elliptic curve cryptography to generate verifiable proof of authentication and authorization. These proofs are lightweight digital signatures, which is shared between client and server to manage permission, protect routes and resources and authenticate users. A typical DID consists of proof and claim. Claim is the unsigned data representing the user's data. And proof is by signing that using Ethereum's personal sign algorithm and using users' private key. And then you get the DID token by calling B2A and using base64 JSON tuple string.

So this is how a basic generating DID token looks like, which consists of issue.expiration, subject, DID, not before time, and all sorts of information over here. The issue is we use the user's public key in the claim. And when we are signing the using sign function, we use the user's private key, which is again, we don't look at those data. And then we encode the DID token so it can be easily transported over HTTP.

The easiest way to get started with Magic is using Magic's client SDK. The client SDK is where you get the DID token. So you use that, pass on the API key, which is like two types of API key. One is the publishable key and another one is the secret key. Secret key is used for server. Publishable key is for client applications. You call a function called login with email, and then pass on the user's email. By default, you will get a DID token of a lifespan of 15 minutes, but if you want more than that, you can call getIDtoken function to get that. The auth flow is that a user calls the client by authenticating himself or herself, they get the DID token, and they trade that DID token in the authorization header to the server, and server validates that token and then allows the protected route.

So let's build the API. Easiest way to get started is to run npx makemagic select the template express API. So I have already done this, and you would see that I ran an application. I'll just showcase what it looks like. For example, npx makemagic template express API, it will ask for your application name, test API, and then you can use the publishable secret key. For example, you can get this secret key by logging in to Magic and signing up, it's free to do that and copy the secret key from the application folder.

2. Securing the Application

Short description:

If you're not seeing this, select your application and reveal the secret key. Once done, your application will be open on port 8080 with multiple routes. The basic route is unprotected, while the secret route is protected by middleware. The isAuthorized function checks the authorization header, extracts the DID token, and validates it. You can get the DID token by running NPX make magic and selecting the next template. Pass the secret key to access protected routes. Feel free to explore the docs at magic and reach out for any questions or issues.

If you're not seeing this, you select this and select your application, and then reveal the secret key. Just paste in here and then select your application, that's it.

And once that is done, it will be open, and it will look something like this. Your application is running on port 8080 so this gives you multiple routes.

Normal route is the basic route, which gives you an unprotected route. Another one is the secret route, which is protected by middleware, which we have wrote, which you can always see by seeing the example. I have already created an application called jsnationnav. Just see this function, you would see that nothing much is happening but this is a very basic API, where we are using magic secret key from the environment variable, we are using a port variable as well, and then we are instantiating the magic here. Then this is a list of to-do, which is simulating the database but obviously you would need a proper database.

So this is an unprotected route, this is a protected route, you protect this by calling isAuthorized. So I'll show how it isAuthorized function looks like. So this is the middleware and these to-do are like unprotected API routes, it's get-request and like get of one id, like getting one, like the first to-do or the second to-do. These are unprotected so another way of using the protected route or the middleware is to use app.use() and pass on the authorization functions, what we have called isAuthorized and then all these routes are by default protected because we are using here.

So if we want to use it the older way, we would have to pass on to all of the functions over here. So let's see how the isAuthorized looks like, it accepts request, response, and next. We check first the authorization header is not defined and then extract the DID token from the header and then we call magic.token.validate() which shows you if there is an error they will say that there is an error and else we would continue by calling next and vice versa. You can find more of the details when you run NPX make magic and this template. So the easiest way to see this is by getting a DID token. The easiest way to get the DID token again to run the NPX make magic and template use the next template which is what I have used and then it will run your server and it will once you log in it will give you a DID token.

So once you do that just pass on the secret key over here and I have pasted this and you would see that this is asking for that like we are allowed and if not we would say that this is failed and it has update, put, delete all sort of restful verbs HTTP verbs. So more on that you can find more. So easiest way to run is by getting the DID token is from the front end by running this particular command npx make magic and selecting a template next. By default next won't give you much help like in terms of DID token. So what I have called is that I have taken a DID here and then calling the get DID token and then displaying the DID token. Feel free to explore the docs at magic and then yeah, this is the resources you can find and learn more about and if you run into any trouble just run npx mdspzalm, my username and then all bunch of information would be there. Feel free to reach out to me if you have any question. So yes, thank you again JS Nation for having me and for a wonderful conference.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Node Congress 2022Node Congress 2022
26 min
It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Top Content
The talk discusses the importance of supply chain security in the open source ecosystem, highlighting the risks of relying on open source code without proper code review. It explores the trend of supply chain attacks and the need for a new approach to detect and block malicious dependencies. The talk also introduces Socket, a tool that assesses the security of packages and provides automation and analysis to protect against malware and supply chain attacks. It emphasizes the need to prioritize security in software development and offers insights into potential solutions such as realms and Deno's command line flags.
Towards a Standard Library for JavaScript Runtimes
Node Congress 2022Node Congress 2022
34 min
Towards a Standard Library for JavaScript Runtimes
Top Content
There is a need for a standard library of APIs for JavaScript runtimes, as there are currently multiple ways to perform fundamental tasks like base64 encoding. JavaScript runtimes have historically lacked a standard library, causing friction and difficulty for developers. The idea of a small core has both benefits and drawbacks, with some runtimes abusing it to limit innovation. There is a misalignment between Node and web browsers in terms of functionality and API standards. The proposal is to involve browser developers in conversations about API standardization and to create a common standard library for JavaScript runtimes.
ESM Loaders: Enhancing Module Loading in Node.js
JSNation 2023JSNation 2023
22 min
ESM Loaders: Enhancing Module Loading in Node.js
ESM Loaders enhance module loading in Node.js by resolving URLs and reading files from the disk. Module loaders can override modules and change how they are found. Enhancing the loading phase involves loading directly from HTTP and loading TypeScript code without building it. The loader in the module URL handles URL resolution and uses fetch to fetch the source code. Loaders can be chained together to load from different sources, transform source code, and resolve URLs differently. The future of module loading enhancements is promising and simple to use.
Out of the Box Node.js Diagnostics
Node Congress 2022Node Congress 2022
34 min
Out of the Box Node.js Diagnostics
This talk covers various techniques for getting diagnostics information out of Node.js, including debugging with environment variables, handling warnings and deprecations, tracing uncaught exceptions and process exit, using the v8 inspector and dev tools, and generating diagnostic reports. The speaker also mentions areas for improvement in Node.js diagnostics and provides resources for learning and contributing. Additionally, the responsibilities of the Technical Steering Committee in the TS community are discussed.
The State of Passwordless Auth on the Web
JSNation 2023JSNation 2023
30 min
The State of Passwordless Auth on the Web
Passwords are terrible and easily hacked, with most people not using password managers. The credential management API and autocomplete attribute can improve user experience and security. Two-factor authentication enhances security but regresses user experience. Passkeys offer a seamless and secure login experience, but browser support may be limited. Recommendations include detecting Passkey support and offering fallbacks to passwords and two-factor authentication.
Node.js Compatibility in Deno
Node Congress 2022Node Congress 2022
34 min
Node.js Compatibility in Deno
Deno aims to provide Node.js compatibility to make migration smoother and easier. While Deno can run apps and libraries offered for Node.js, not all are supported yet. There are trade-offs to consider, such as incompatible APIs and a less ideal developer experience. Deno is working on improving compatibility and the transition process. Efforts include porting Node.js modules, exploring a superset approach, and transparent package installation from npm.

Workshops on related topic

Node.js Masterclass
Node Congress 2023Node Congress 2023
109 min
Node.js Masterclass
Top Content
Workshop
Matteo Collina
Matteo Collina
Have you ever struggled with designing and structuring your Node.js applications? Building applications that are well organised, testable and extendable is not always easy. It can often turn out to be a lot more complicated than you expect it to be. In this live event Matteo will show you how he builds Node.js applications from scratch. You’ll learn how he approaches application design, and the philosophies that he applies to create modular, maintainable and effective applications.

Level: intermediate
Build and Deploy a Backend With Fastify & Platformatic
JSNation 2023JSNation 2023
104 min
Build and Deploy a Backend With Fastify & Platformatic
WorkshopFree
Matteo Collina
Matteo Collina
Platformatic allows you to rapidly develop GraphQL and REST APIs with minimal effort. The best part is that it also allows you to unleash the full potential of Node.js and Fastify whenever you need to. You can fully customise a Platformatic application by writing your own additional features and plugins. In the workshop, we’ll cover both our Open Source modules and our Cloud offering:- Platformatic OSS (open-source software) — Tools and libraries for rapidly building robust applications with Node.js (https://oss.platformatic.dev/).- Platformatic Cloud (currently in beta) — Our hosting platform that includes features such as preview apps, built-in metrics and integration with your Git flow (https://platformatic.dev/). 
In this workshop you'll learn how to develop APIs with Fastify and deploy them to the Platformatic Cloud.
0 to Auth in an hour with ReactJS
React Summit 2023React Summit 2023
56 min
0 to Auth in an hour with ReactJS
WorkshopFree
Kevin Gao
Kevin Gao
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool. There are multiple alternatives that are much better than passwords to identify and authenticate your users - including SSO, SAML, OAuth, Magic Links, One-Time Passwords, and Authenticator Apps.
While addressing security aspects and avoiding common pitfalls, we will enhance a full-stack JS application (Node.js backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session securely for subsequent client requests, validating / refreshing sessions- Basic Authorization - extracting and validating claims from the session token JWT and handling authorization in backend flows
At the end of the workshop, we will also touch other approaches of authentication implementation with Descope - using frontend or backend SDKs.
Building a Hyper Fast Web Server with Deno
JSNation Live 2021JSNation Live 2021
156 min
Building a Hyper Fast Web Server with Deno
WorkshopFree
Matt Landers
Will Johnston
2 authors
Deno 1.9 introduced a new web server API that takes advantage of Hyper, a fast and correct HTTP implementation for Rust. Using this API instead of the std/http implementation increases performance and provides support for HTTP2. In this workshop, learn how to create a web server utilizing Hyper under the hood and boost the performance for your web apps.
0 to Auth in an Hour Using NodeJS SDK
Node Congress 2023Node Congress 2023
63 min
0 to Auth in an Hour Using NodeJS SDK
WorkshopFree
Asaf Shen
Asaf Shen
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool.
We will enhance a full-stack JS application (Node.JS backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session for subsequent client requests, validating / refreshing sessions
At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods.
Table of contents- A quick intro to core authentication concepts- Coding- Why passwordless matters
Prerequisites- IDE for your choice- Node 18 or higher
GraphQL - From Zero to Hero in 3 hours
React Summit 2022React Summit 2022
164 min
GraphQL - From Zero to Hero in 3 hours
Workshop
Pawel Sawicki
Pawel Sawicki
How to build a fullstack GraphQL application (Postgres + NestJs + React) in the shortest time possible.
All beginnings are hard. Even harder than choosing the technology is often developing a suitable architecture. Especially when it comes to GraphQL.
In this workshop, you will get a variety of best practices that you would normally have to work through over a number of projects - all in just three hours.
If you've always wanted to participate in a hackathon to get something up and running in the shortest amount of time - then take an active part in this workshop, and participate in the thought processes of the trainer.