473,287 Members | 1,643 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,287 developers and data experts.

Securing Nodejs Microservices with Oauth

As part of the Oauth architecture, we have an authorization server that acts as middleman in handling all the permissions very clearly. Instead of providing credentials to another application to access your resources, with Oauth we’ll provide a key that this application will use to retrieve a token with a very specific set of permissions called scopes. The scopes are a representation of our resources in the resource server.

This is an example of how the Oauth flow works, as you can see in the following diagram.

The application that needs access to a specific resource server makes a call to the Oauth Authorization Server first, with the client id and secret previously shared with the application by the authorization server. The scope in this case should represent the service that the application wants to access.

If all goes well, the Oauth Authorization Server will push back an access token, valid only for a specific timeframe and only to access the resource specified in the scope.

The application is now able to call the resource server (our services) by including the token in the authorization header of each call.

Oauth tokens

Oauth security is based on access tokens for authorization, so let's talk about the different types of tokens that are used by this standard and some particularities about them.

Access token

The access tokens are the mechanism that the applications will use to access an API or service on behalf of a user. This token represents the authorization of a specific application to access an specific part of information on the service and they are short-lived.

The access token is very sensitive information and we should keep it in a very secure way, so it should only be accessed via the resource server, the authorization server and the application itself.

All the tokens are usually represented with the JWT standard (JSON Web Tokens).

JWT
A JWT (pronounced 'jot') is a secure and trustworthy standard for token authentication. JWTs allow you to digitally sign information (referred to as claims) with a signature and can be verified at a later time with a secret signing key.

Refresh token

This one can live more time, as in days, months, or even years. It can be used to get new tokens. To get a refresh token, applications typically require confidential clients with authentication.

OpenIdConnect
Oauth can be combined with another standard called SAML, OpenID Connect (OIDC) extends OAuth 2.0 with a new signed id_token for the client to be able to get more information about the users directly from the token.

How can we implement Oauth?
So this is great, but how can we implement this standard?, well Oauth can be implemented in two ways: on your own, or via third-parties.

Implementing on your own is maybe the hardest option, as you will need to create and maintain the authorization server from your end. However, it also has some advantages as you will have more control over the authorization piece and we can take advantage of libraries that are available in any programming language.

For NodeJS we have oauth2-server - open source, simple, and easy to integrate with your Node apps (even if they’ve already been running for a while).

In the docs, you will find the official Model Specification that describes how your JS code must override the default OAuth2 functions to provide your customized auth experience.

With the OAuth2Server object, you can override the default OAuth2 provider by the Express server. Then, we can easily provide your own auth experience.

Another way to use Oauth is by entrusting a third-party with providing the desired level of security. Oauth is based on access tokens for authentication and authorization - Okta, for instance.

Lets see all of this in an example specifically to secure a nodeJS service.

Practical example
All the code is available here and you will also need to have nodejs installed.

First of all, let's create a very simple nodeJS application: create a folder called 'node-oauth-test', then open a terminal in that folder and execute the following command:

Expand|Select|Wrap|Line Numbers
  1. npm init
After providing all the required information, a package.json file will be created for you. Then we need to add a very simple code for our nodejs 'hello word' example.

To do this, you have to create a new file, index.js, and add this:

Expand|Select|Wrap|Line Numbers
  1. const express = require('express')
  2. const bodyParser = require('body-parser')
  3. const { promisify } = require('util')
  4. const app = express()
  5.  
  6. app.use(bodyParser.json())
  7.  
  8. app.get('/', (req, res) => {
  9.     res.status(200).send('Hello, world!').end();
  10. });
  11.  
  12. const startServer = async () => {
  13.     const port = process.env.SERVER_PORT || 8080
  14.     await promisify(app.listen).bind(app)(port)
  15.     console.log(`Listening on port ${port}`)
  16. }
  17.  
  18. startServer()
The code is self-explanatory but in this case we are using a library called ExpressJS to create our first hello world path.

To install express, type

Expand|Select|Wrap|Line Numbers
  1. npm install express util
The next step is to run your NodeJS application for the first time, by executing the following:

Expand|Select|Wrap|Line Numbers
  1. `node.
  2. `C:\Users\pablo.portillo\Documents\VSworkspace\node-oauth-test>node 
  3. Listening on port 8080` 
Now we should see our application running in port 8080 directly in our browsers.
Jul 15 '21 #1
0 4104

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: gollapudiramya | last post by:
Hi, Can any body help to create oauth sample webapplication in C#. I need the complete source code that should use oauth libraries.
1
HaLo2FrEeEk
by: HaLo2FrEeEk | last post by:
I've been using a PHP Twitter library for months now to automatically repost news that I post on my site, to my site's Twitter. Recently though this stopped working, and I get an error back from...
1
by: Don Clemens | last post by:
Ok, so I downloaded a class online (OAuthBase.cs). Every time I plug it into my project, I am getting "The name 'HttpUtility' does not exist in the current context" error. I got this from the...
0
by: michaeldebruin | last post by:
Hello all, Any of you who knows how to establish a oAuth connection to an API using Silverlight? Any help or tips would be appreciated. Thanks in advance Michael
0
by: saikrishna123 | last post by:
-1 down vote favorite 1 Hii im doing linkedin oauth sign in using php. Im struck at getting details like phone number and date of birth from linkedin account.Im getting all other details. ...
7
by: tdrsam | last post by:
I'm trying to add a MongoDb database to a nodejs app. I've never done this before and don't know how it works. I seem to have the Db installed, but I don't seem to be able to send data to it from a...
1
by: AjayGohil | last post by:
What is OAuth in Web API?
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.