@@ -2,7 +2,13 @@ const express = require("express");
2
2
const cors = require ( "cors" ) ;
3
3
const morgan = require ( "morgan" ) ;
4
4
const 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" ) ;
6
12
const authConfig = require ( "./src/auth_config.json" ) ;
7
13
8
14
const app = express ( ) ;
@@ -11,11 +17,7 @@ const port = process.env.API_PORT || 3001;
11
17
const appPort = process . env . SERVER_PORT || 3000 ;
12
18
const appOrigin = authConfig . appOrigin || `http://localhost:${ appPort } ` ;
13
19
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" ) {
19
21
console . log (
20
22
"Exiting: Please make sure that auth_config.json is in place and populated with valid domain and audience values"
21
23
) ;
@@ -27,16 +29,35 @@ app.use(morgan("dev"));
27
29
app . use ( helmet ( ) ) ;
28
30
app . use ( cors ( { origin : appOrigin } ) ) ;
29
31
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
+ ) ;
35
39
36
- app . get ( "/api/external" , checkJwt , ( req , res ) => {
40
+ app . get ( "/api/external" , requiredScopes ( 'admin' ) , ( req , res ) => {
37
41
res . send ( {
38
42
msg : "Your access token was successfully validated!" ,
39
43
} ) ;
40
44
} ) ;
41
45
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
+
42
63
app . listen ( port , ( ) => console . log ( `API Server listening on port ${ port } ` ) ) ;
0 commit comments