Falcor API: Authentication

View on Github

Falcor API: Authentication

Community maintained

This tutorial will show you how to add authorization to a Falcor API. We recommend you to Log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it on Github.

View on Github
System requirements: Falcor 0.1.17 | Express 4.15.2

New to Auth0? Learn how Auth0 works and read about implementing API authentication and authorization using the OAuth 2.0 framework.

Configure Auth0 APIs

Create an API

In the APIs section of the Auth0 dashboard, click Create API. Provide a name and an identifier for your API, for example https://quickstarts/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

By default, your API uses RS256 as the algorithm for signing tokens. Since RS256 uses a private/public keypair, it verifies the tokens against the public key for your Auth0 account. The public key is in the JSON Web Key Set (JWKS) format, and can be accessed here.

Define scopes

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

You can add the required scopes in the Scopes tab of the Auth0 Dashboard's APIs section.

Configure Scopes

This example uses the read:messages scope.

This example demonstrates:

  • How to check for a JSON Web Token (JWT) in the Authorization header of an incoming HTTP request.

  • How to check if the token is valid, using the JSON Web Key Set (JWKS) for your Auth0 account. To learn more about validating Access Tokens, read the Verify Access Tokens tutorial.

Validate Access Tokens

Add 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

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']
});

Protect API Endpoints

The routes shown below are available for the following requests:

  • GET /api/public: available for non-authenticated requests
  • GET /api/private: available for authenticated requests containing an Access Token with no additional scopes
  • GET /api/private-scoped: available for authenticated requests containing an Access Token with the read:messages scope granted

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 FREE