DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Databases
  4. Developing RESTful APIs With Loopback, Part 2: Securing Your API

Developing RESTful APIs With Loopback, Part 2: Securing Your API

In this tutorial, we'll show you how to secure the RESTful API we designed in Part 1, using JSON Web Tokens and a free tool (along with some JavaScript).

Prosper Otemuyiwa user avatar by
Prosper Otemuyiwa
·
Sep. 15, 17 · Tutorial
Like (4)
Save
Tweet
Share
9.44K Views

Join the DZone community and get the full member experience.

Join For Free

Welcome back! If you missed Part 1, check it out here!

Secure the Star Wars API

The majority of the APIs we use on a daily basis have a means of authorizing users to make changes to them. We'll go ahead and secure some of these API endpoints with JSON Web Tokens.

JSON Web Tokens, commonly known as JWTs, are tokens that are used to authenticate users on applications. This technology has gained popularity over the past few years because it enables backends to accept requests simply by validating the contents of these JWTs. That is, applications that use JWTs no longer have to hold cookies or other session data about their users. This characteristic facilitates scalability while keeping applications secure.

Whenever the user wants to access a protected route or resource (an endpoint), the user agent must send the JWT, usually in the Authorization header using the Bearer schema, along with the request.

When the API receives a request with a JWT, the first thing it does is to validate the token. This consists of a series of steps, and if any of these fails then, the request must be rejected. The following list shows the validation steps needed:

  • Check that the JWT is well formed.
  • Check the signature.
  • Validate the standard claims.
  • Check the Client permissions (scopes).

More information about JWTs can be found here.

Now, we will make use of Auth0 to issue our JSON Web Tokens. With Auth0, we have to write just a few lines of code to get a solid identity management solution, including single sign-on, user management, support for social identity providers (like Facebook, GitHub, Twitter, etc.), enterprise (Active Directory, LDAP, SAML, etc.), and your own database of users.

For starters, if you haven't done so yet, this is a good time to sign up for a free Auth0 account. Having an Auth0 account, the first thing that we must do is to create a new API on the dashboard. An API is an entity that represents an external resource, capable of accepting and responding to protected resource requests made by clients. And we are dealing with an API here, SWAPI (Star Wars API).

Login to your Auth0 management dashboard and create a new API client.

Click on the APIs menu item and then the Create API button. You will need to give your API a name and an identifier. The name can be anything you choose, so make it as descriptive as you want. The identifier will be used to identify your API, this field cannot be changed once set. For our example, I'll name the API, Star Wars API, and for the identifier, I'll set it as https://starwarsapi.com. We'll leave the signing algorithm as RS256 and click on the Create API button.

Create a New API

Creating the Star Wars API

You can define scopes in this section

Head over to your terminal and install the following node modules:

npm install express-jwt jwks-rsa --save

Open up your server/server.js file and modify the code to look like this:

'use strict';

var loopback = require('loopback');
var boot = require('loopback-boot');
var jwt = require('express-jwt');
var jwks = require('jwks-rsa');

var app = module.exports = loopback();

var authCheck = jwt({
  secret: jwks.expressJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        // YOUR-AUTH0-DOMAIN name e.g https://prosper.auth0.com
        jwksUri: "{YOUR-AUTH0-DOMAIN}/.well-known/jwks.json"
    }),
    // This is the identifier we set when we created the API
    audience: '{YOUR-API-AUDIENCE-ATTRIBUTE}',
    issuer: '{YOUR-AUTH0-DOMAIN}',
    algorithms: ['RS256']
});


app.use(authCheck);

// apply to a path
app.use('/api/films', function(req, res, next) {
    res.json("It has valid token", req.user);
});

// catch error
app.use(function (err, req, res, next) {
    if (err.name === 'UnauthorizedError') {
        res.status(401).send('Invalid token, or no token supplied!');
    } else {
        res.status(401).send(err);
    }
});


app.start = function() {
  // start the web server
  return app.listen(function() {
    app.emit('started');
    var baseUrl = app.get('url').replace(/\/$/, '');
    console.log('Web server listening at: %s', baseUrl);
    if (app.get('loopback-component-explorer')) {
      var explorerPath = app.get('loopback-component-explorer').mountPath;
      console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
    }
  });
};

// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
  if (err) throw err;

  // start the server if `$ node server.js`
  if (require.main === module)
    app.start();
});

In the code above, we required express-jwt and jwks-rsa modules.

  • The expres-jwt module is an express middleware that validates a JSON Web Token and set the req.user with the attributes.
  • The jwks-rsa module is a library that helps retrieve RSA public keys from a JSON Web Key Set endpoint.

The authCheck variable does the check to validate the access tokens that are sent as Authorization headers. It validates the audience, issuer and algorithm used to sign the token.

Note: Replace the YOUR-API-AUDIENCE-ATTRIBUTE and YOUR-AUTH0-DOMAIN placeholders with the API audience and Auth0 domain values from your Auth0 dashboard.

Here, we used authCheck as a middleware. So, if a user accesses any API endpoint/route without a valid access token or no token at all, it returns an error. Try it out.

Accessing the species endpoint without a token

Now, let's test it with a valid access token. Head over to the test tab of your newly created API on your Auth0 dashboard.

Click on the Test tab

Grab the Access token.

Grab the Access Token

Now use this access token in Postman by sending it as an Authorization header to accessapi/species endpoint.

Accessing the endpoint securely

Aha! It validates the access token and returns the right data.

Wondering how to integrate the secure API with a front-end? Check out our amazing React(Part 1, Part 2, and Part 3), and Vue.js authentication tutorials.

Conclusion

Loopback is a great Node.js framework that can be used to design and build your APIs quickly, as shown in this tutorial. It is a project backed up by IBM and the Strongloop team. They are committed to maintaining and improving on this amazing open source project.

API

Published at DZone with permission of Prosper Otemuyiwa, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • API Design Patterns Review
  • 7 Awesome Libraries for Java Unit and Integration Testing
  • What Is a Kubernetes CI/CD Pipeline?
  • Deploying Java Serverless Functions as AWS Lambda

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: