Falcor API: Authentication

Community maintained

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

System Requirements
  • Falcor 0.1.17
  • Express 4.15.2
Show requirements

This tutorial shows you how to use the authorization features in the OAuth 2.0 framework to limit access to your or third-party applications. For more information, read the API authorization documentation.

Create a Resource Server (API)

In the APIs section of the Auth0 dashboard, click Create API. Provide a name and an identifier for your API. You will use the identifier as an audience later, when you are configuring the Access Token verification. For Signing Algorithm, select RS256.

Create API

Add API Authorization

To restrict access to the resources served by your API, check the incoming requests for valid authorization information. The authorization information is stored in the Access Token created for the user and needs to be sent in the Authorization header. To see if the token is valid, check it against the JSON Web Key Set (JWKS) for your Auth0 account. To learn more about validating Access Tokens, read the Verify Access Tokens tutorial.

Add the Dependencies

Add express-jwt, express-jwt-authz, falcor-express, falcor-router, and falcor-http-datasource to your project.

npm install express-jwt express-jwt-authz falcor-express falcor-router falcor-http-datasource --save

Configuration

By default, your API will be set up to use RS256 as the algorithm for signing tokens. Since RS256 works by using a private/public keypair, tokens can be verified against the public key for your Auth0 account. This public key is accessible at https://YOUR_AUTH0_DOMAIN/.well-known/jwks.json.

Configure the express-jwt middleware to use the remote JWKS for your Auth0 account.

// server.js

const express = require('express');
const app = express();
const jwt = require('express-jwt');
const jwksRsa = require('jwks-rsa');
const falcorExpress = require('falcor-express');
const Router = require('falcor-router');

// Authentication middleware. When used, the
// access token must exist and be verified against
// the Auth0 JSON Web Key Set
const authenticate = jwt({
  // Dynamically provide a signing key
  // based on the kid in the header and 
  // the singing keys provided by the JWKS endpoint.
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https://YOUR_AUTH0_DOMAIN/.well-known/jwks.json`
  }),

  // Validate the audience and the issuer.
  audience: '{YOUR_API_IDENTIFIER}',
  issuer: `https://YOUR_AUTH0_DOMAIN/`,
  algorithms: ['RS256']
});
// api.js

const express = require('express');
const app = express();
const jwt = require('express-jwt');
const jwksRsa = require('jwks-rsa');
const falcor = require('falcor');
const HttpDataSource = require('falcor-http-datasource');

const checkJwt = jwt({
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https:///.well-known/jwks.json`
  }),

  audience: process.env.AUTH0_AUDIENCE,
  issuer: `https:///`,
  algorithms: ['RS256']
});

Configure the Scopes

Scopes let you define which resources can be accessed by the user with a given Access Token. For example, you might choose to give the read access to the messages resource if a user has the manager access level, and a write access to that resource if they have the administrator access level.

To configure scopes, in your Auth0 dashboard, in the APIs section, click the Scopes tab. Configure the scopes you need.

Configure Scopes

This example uses the read:messages scope.

Secure your API

To protect an individual route that requires a valid JWT, configure the route with the checkJwt express-jwt middleware.

// server.js

// This endpoints doesn't need authentication
app.use('/api/public/model.json', falcorExpress.dataSourceRoute(function(req, res) {
  return new Router([
    {
      route: 'public.message',
      get: function(pathSet) {
        return { path:['public', 'message'], value: 'Hello from a public endpoint! You don\'t need to be authenticated to see this.' };
      }
    }
  ]);
}));

app.use('/api/private/model.json', checkJwt, falcorExpress.dataSourceRoute(function(req, res) {
  return new Router([
    {
      route: "private.message",
      get: function(pathSet) {
        return { path:['private', 'message'], value: 'Hello from a private endpoint! You need to be authenticated to see this.' };
      }
    }
  ]);
}));
// api.js

// This endpoints doesn't need authentication
app.get('/api/public', async function(req, res) {
  const model = new falcor.Model(
    {
      source: new HttpDataSource('http://localhost:3000/api/public/model.json')
    });

  const message = await model.getValue(['public', 'message']);

  res.json({ message: message });
});

app.get('/api/private', checkJwt, async function(req, res) {
  const token = req.headers.authorization.split(" ")[1];
  const model = new falcor.Model(
    {
      source: new HttpDataSource(
        'http://localhost:3000/api/private/model.json',
        {
          headers: { 'Authorization': 'Bearer ' + token }
        })
    });

  const message = await model.getValue(['private', 'message']);

  res.json({ message: message });
});

If you are following along with the sample project you downloaded from the top of this page, base URL for Falcor's model should be set to http://localhost:3000.

Individual routes can be configured to look for a particular scope by setting up another middleware with the express-jwt-authz package. To do so, provide an array of required scopes and apply the middleware to any routes you wish to add authorization to.

// server.js

const checkScopes = jwtAuthz([ 'read:messages' ]);

app.use('/api/private-scoped/model.json', checkJwt, checkScopes, falcorExpress.dataSourceRoute(function(req, res) {
  return new Router([
    {
      route: 'private_scoped.message',
      get: function(pathSet) {
        return { path:['private_scoped', 'message'], value: 'Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this.' };
      }
    }
  ]);
}));
// api.js

app.get('/api/private-scoped', checkJwt, async function(req, res) {
  const token = req.headers.authorization.split(' ')[1];
  const model = new falcor.Model(
    {
      source: new HttpDataSource(
        'http://localhost:3000/api/private-scoped/model.json',
        {
          headers: { 'Authorization': 'Bearer ' + token }
        })
    });

  try {
    const message = await model.getValue(['private_scoped', 'message']);

    res.json({ message: message });
  } catch(err) {
    res.status(403).json(err[0].value);
  }
});

Optional steps

Configuring CORS

If you want to configure CORS, add this code to your Falcor app (assuming your Falcor app is hosted on http://localhost:3010):

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:3010");
  res.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Credentials", "true");
  next();
});
Use Auth0 for FREECreate free Account