Service Setup
To get started, let's create a new folder called service
under the React application folder. cd
into the folder and run:
yarn init -y
yarn add express express-jwt jwks-rsa cors @aserto/aserto-node dotenv
To the .env
file we created previously, we'll add the following:
JWKS_URI=https://acmecorp.demo.aserto.com/dex/keys
ISSUER=https://acmecorp.demo.aserto.com/dex
AUDIENCE=acmecorp-app
In the service
folder, Create a file called api.js
- that will be our server. To this file, we'll add the following dependencies:
require('dotenv').config()
const express = require('express')
const jwt = require('express-jwt')
const jwksRsa = require('jwks-rsa')
const cors = require('cors')
const app = express()
In the next section we define the middleware function which will call our identity provider to verify the validity of the JWT (and also enable CORS): Express.js will pass the call to the checkJwt
middleware which will determine whether the JWT sent to it is valid or not. If it is not valid, Express.js will return a 403 (Forbidden) response.
//Paste after the dependencies
const checkJwt = jwt({
// Dynamically provide a signing key based on the kid in the header and the signing keys provided by the JWKS endpoint
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: process.env.JWKS_URI,
}),
// Validate the audience and the issuer
audience: process.env.AUDIENCE,
issuer: process.env.ISSUER,
algorithms: ['RS256'],
})
Lastly, we set up a protected route which will use the checkJwt
middleware:
// Enable CORS
app.use(cors())
// Protected API endpoint
app.get('/api/protected', checkJwt, function (req, res) {
//send the response
res.json({
secretMessage: 'Here you go, very sensitive information for ya!',
})
})
// Launch the API Server at localhost:8080
app.listen(8080)
Awesome! our service will be listening on port 8080 and we set up a protected endpoint. In the next section we'll test this endpoint by updating our application to send a JWT token.