@@ -2,7 +2,13 @@ const express = require("express");
22const cors = require ( "cors" ) ;
33const morgan = require ( "morgan" ) ;
44const helmet = require ( "helmet" ) ;
5- const { auth } = require ( "express-oauth2-jwt-bearer" ) ;
5+ const {
6+ auth,
7+ InvalidTokenError,
8+ InvalidRequestError,
9+ InsufficientScopeError,
10+ requiredScopes,
11+ } = require ( "express-oauth2-jwt-bearer" ) ;
612const authConfig = require ( "./src/auth_config.json" ) ;
713
814const app = express ( ) ;
@@ -11,11 +17,7 @@ const port = process.env.API_PORT || 3001;
1117const appPort = process . env . SERVER_PORT || 3000 ;
1218const appOrigin = authConfig . appOrigin || `http://localhost:${ appPort } ` ;
1319
14- if (
15- ! authConfig . domain ||
16- ! authConfig . audience ||
17- authConfig . audience === "YOUR_API_IDENTIFIER"
18- ) {
20+ if ( ! authConfig . domain || ! authConfig . audience || authConfig . audience === "YOUR_API_IDENTIFIER" ) {
1921 console . log (
2022 "Exiting: Please make sure that auth_config.json is in place and populated with valid domain and audience values"
2123 ) ;
@@ -27,16 +29,35 @@ app.use(morgan("dev"));
2729app . use ( helmet ( ) ) ;
2830app . use ( cors ( { origin : appOrigin } ) ) ;
2931
30- const checkJwt = auth ( {
31- audience : authConfig . audience ,
32- issuerBaseURL : `https://${ authConfig . domain } /` ,
33- algorithms : [ "RS256" ] ,
34- } ) ;
32+ app . use (
33+ auth ( {
34+ audience : authConfig . audience ,
35+ issuerBaseURL : `https://${ authConfig . domain } /` ,
36+ algorithms : [ "RS256" ] ,
37+ } )
38+ ) ;
3539
36- app . get ( "/api/external" , checkJwt , ( req , res ) => {
40+ app . get ( "/api/external" , requiredScopes ( 'admin' ) , ( req , res ) => {
3741 res . send ( {
3842 msg : "Your access token was successfully validated!" ,
3943 } ) ;
4044} ) ;
4145
46+ // Custom error handler that will turn the errors from express-oauth2-jwt-bearer into a JSON object
47+ // for the UI to handle
48+ app . use ( ( err , req , res , next ) => {
49+ if (
50+ err instanceof InvalidTokenError ||
51+ err instanceof InvalidRequestError ||
52+ err instanceof InsufficientScopeError
53+ ) {
54+ return res . status ( err . status ) . send ( {
55+ error : err . code ,
56+ message : err . message ,
57+ } ) ;
58+ }
59+
60+ res . send ( err ) ;
61+ } ) ;
62+
4263app . listen ( port , ( ) => console . log ( `API Server listening on port ${ port } ` ) ) ;
0 commit comments