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.

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
Do you know what’s really going on in your node_modules folder? Software supply chain attacks have exploded over the past 12 months and they’re only accelerating in 2022 and beyond. We’ll dive into examples of recent supply chain attacks and what concrete steps you can take to protect your team from this emerging threat.
You can check the slides for Feross' talk here.
Towards a Standard Library for JavaScript Runtimes
Node Congress 2022Node Congress 2022
34 min
Towards a Standard Library for JavaScript Runtimes
Top Content
You can check the slides for James' talk here.
ESM Loaders: Enhancing Module Loading in Node.js
JSNation 2023JSNation 2023
22 min
ESM Loaders: Enhancing Module Loading in Node.js
Native ESM support for Node.js was a chance for the Node.js project to release official support for enhancing the module loading experience, to enable use cases such as on the fly transpilation, module stubbing, support for loading modules from HTTP, and monitoring.
While CommonJS has support for all this, it was never officially supported and was done by hacking into the Node.js runtime code. ESM has fixed all this. We will look at the architecture of ESM loading in Node.js, and discuss the loader API that supports enhancing it. We will also look into advanced features such as loader chaining and off thread execution.
Out of the Box Node.js Diagnostics
Node Congress 2022Node Congress 2022
34 min
Out of the Box Node.js Diagnostics
In the early years of Node.js, diagnostics and debugging were considerable pain points. Modern versions of Node have improved considerably in these areas. Features like async stack traces, heap snapshots, and CPU profiling no longer require third party modules or modifications to application source code. This talk explores the various diagnostic features that have recently been built into Node.
You can check the slides for Colin's talk here. 
The State of Passwordless Auth on the Web
JSNation 2023JSNation 2023
30 min
The State of Passwordless Auth on the Web
Can we get rid of passwords yet? They make for a poor user experience and users are notoriously bad with them. The advent of WebAuthn has brought a passwordless world closer, but where do we really stand?
In this talk we'll explore the current user experience of WebAuthn and the requirements a user has to fulfill for them to authenticate without a password. We'll also explore the fallbacks and safeguards we can use to make the password experience better and more secure. By the end of the session you'll have a vision for how authentication could look in the future and a blueprint for how to build the best auth experience today.
Node.js Compatibility in Deno
Node Congress 2022Node Congress 2022
34 min
Node.js Compatibility in Deno
Can Deno run apps and libraries authored for Node.js? What are the tradeoffs? How does it work? What’s next?

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
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.
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 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
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.
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.