Securing Nodejs Microservices with Oauth

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ioana budai
    New Member
    • May 2021
    • 1

    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:

    Code:
    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:

    Code:
    const express = require('express')
    const bodyParser = require('body-parser')
    const { promisify } = require('util')
    const app = express()
    
    app.use(bodyParser.json())
    
    app.get('/', (req, res) => {
        res.status(200).send('Hello, world!').end();
    });
    
    const startServer = async () => {
        const port = process.env.SERVER_PORT || 8080
        await promisify(app.listen).bind(app)(port)
        console.log(`Listening on port ${port}`)
    }
    
    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

    Code:
    npm install express util
    The next step is to run your NodeJS application for the first time, by executing the following:

    Code:
    `node.
    `C:\Users\pablo.portillo\Documents\VSworkspace\node-oauth-test>node 
    Listening on port 8080`
    Now we should see our application running in port 8080 directly in our browsers.
Working...