|
| 1 | +const express = require('express'); |
| 2 | +const morgan = require('morgan'); |
| 3 | +const cors = require('cors'); |
| 4 | + |
| 5 | +const rateLimit = require('express-rate-limit'); |
| 6 | + |
| 7 | +const passport = require('passport'); |
| 8 | +const passportAzureAd = require('passport-azure-ad'); |
| 9 | + |
| 10 | + |
| 11 | +const authConfig = require('./authConfig.js'); |
| 12 | +const router = require('./routes/index'); |
| 13 | + |
| 14 | +const app = express(); |
| 15 | + |
| 16 | +/** |
| 17 | + * If your app is behind a proxy, reverse proxy or a load balancer, consider |
| 18 | + * letting express know that you are behind that proxy. To do so, uncomment |
| 19 | + * the line below. |
| 20 | + */ |
| 21 | + |
| 22 | +// app.set('trust proxy', /* numberOfProxies */); |
| 23 | + |
| 24 | +/** |
| 25 | + * HTTP request handlers should not perform expensive operations such as accessing the file system, |
| 26 | + * executing an operating system command or interacting with a database without limiting the rate at |
| 27 | + * which requests are accepted. Otherwise, the application becomes vulnerable to denial-of-service attacks |
| 28 | + * where an attacker can cause the application to crash or become unresponsive by issuing a large number of |
| 29 | + * requests at the same time. For more information, visit: https://cheatsheetseries.owasp.org/cheatsheets/Denial_of_Service_Cheat_Sheet.html |
| 30 | + */ |
| 31 | +const limiter = rateLimit({ |
| 32 | + windowMs: 15 * 60 * 1000, // 15 minutes |
| 33 | + max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes) |
| 34 | + standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers |
| 35 | + legacyHeaders: false, // Disable the `X-RateLimit-*` headers |
| 36 | +}); |
| 37 | + |
| 38 | +// Apply the rate limiting middleware to all requests |
| 39 | +app.use(limiter); |
| 40 | + |
| 41 | +app.use(cors()); |
| 42 | + |
| 43 | +app.use(express.json()) |
| 44 | +app.use(express.urlencoded({ extended: false})); |
| 45 | +app.use(morgan('dev')); |
| 46 | + |
| 47 | +const options = { |
| 48 | + identityMetadata: `https://${authConfig.metadata.b2cDomain}/${authConfig.credentials.tenantName}/${authConfig.policies.policyName}/${authConfig.metadata.version}/${authConfig.metadata.discovery}`, |
| 49 | + clientID: authConfig.credentials.clientID, |
| 50 | + audience: authConfig.credentials.clientID, |
| 51 | + policyName: authConfig.policies.policyName, |
| 52 | + isB2C: authConfig.settings.isB2C, |
| 53 | + validateIssuer: authConfig.settings.validateIssuer, |
| 54 | + loggingLevel: authConfig.settings.loggingLevel, |
| 55 | + passReqToCallback: authConfig.settings.passReqToCallback, |
| 56 | + loggingNoPII: authConfig.settings.loggingNoPII, // set this to true in the authConfig.js if you want to enable logging and debugging |
| 57 | +}; |
| 58 | + |
| 59 | +const bearerStrategy = new passportAzureAd.BearerStrategy(options, (req,token, done) => { |
| 60 | + /** |
| 61 | + * Below you can do extended token validation and check for additional claims, such as: |
| 62 | + * - check if the delegated permissions in the 'scp' are the same as the ones declared in the application registration. |
| 63 | + * |
| 64 | + * Bear in mind that you can do any of the above checks within the individual routes and/or controllers as well. |
| 65 | + * For more information, visit: https://learn.microsoft.com/en-us/azure/active-directory-b2c/tokens-overview |
| 66 | + */ |
| 67 | + |
| 68 | + /** |
| 69 | + * Lines below verifies if the caller's client ID is in the list of allowed clients. |
| 70 | + * This ensures only the applications with the right client ID can access this API. |
| 71 | + * To do so, we use "azp" claim in the access token. Uncomment the lines below to enable this check. |
| 72 | + */ |
| 73 | + // if (!myAllowedClientsList.includes(token.azp)) { |
| 74 | + // return done(new Error('Unauthorized'), {}, "Client not allowed"); |
| 75 | + // } |
| 76 | + |
| 77 | + // const myAllowedClientsList = [ |
| 78 | + // /* add here the client IDs of the applications that are allowed to call this API */ |
| 79 | + // ] |
| 80 | + |
| 81 | + /** |
| 82 | + * Access tokens that have no 'scp' (for delegated permissions). |
| 83 | + */ |
| 84 | + if (!token.hasOwnProperty('scp')) { |
| 85 | + return done(new Error('Unauthorized'), null, 'No delegated permissions found'); |
| 86 | + } |
| 87 | + |
| 88 | + done(null, {}, token); |
| 89 | +}); |
| 90 | + |
| 91 | + |
| 92 | +app.use(passport.initialize()); |
| 93 | + |
| 94 | +passport.use(bearerStrategy); |
| 95 | + |
| 96 | +app.use( |
| 97 | + '/api', |
| 98 | + (req, res, next) => { |
| 99 | + passport.authenticate( |
| 100 | + 'oauth-bearer', |
| 101 | + { |
| 102 | + session: false, |
| 103 | + }, |
| 104 | + (err, user, info) => { |
| 105 | + if (err) { |
| 106 | + /** |
| 107 | + * An error occurred during authorization. Either pass the error to the next function |
| 108 | + * for Express error handler to handle, or send a response with the appropriate status code. |
| 109 | + */ |
| 110 | + return res.status(401).json({ error: err.message }); |
| 111 | + } |
| 112 | + |
| 113 | + if (!user) { |
| 114 | + // If no user object found, send a 401 response. |
| 115 | + return res.status(401).json({ error: 'Unauthorized' }); |
| 116 | + } |
| 117 | + |
| 118 | + if (info) { |
| 119 | + // access token payload will be available in req.authInfo downstream |
| 120 | + req.authInfo = info; |
| 121 | + return next(); |
| 122 | + } |
| 123 | + } |
| 124 | + )(req, res, next); |
| 125 | + }, |
| 126 | + router, // the router with all the routes |
| 127 | + (err, req, res, next) => { |
| 128 | + /** |
| 129 | + * Add your custom error handling logic here. For more information, see: |
| 130 | + * http://expressjs.com/en/guide/error-handling.html |
| 131 | + */ |
| 132 | + |
| 133 | + // set locals, only providing error in development |
| 134 | + res.locals.message = err.message; |
| 135 | + res.locals.error = req.app.get('env') === 'development' ? err : {}; |
| 136 | + |
| 137 | + // send error response |
| 138 | + res.status(err.status || 500).send(err); |
| 139 | + } |
| 140 | +); |
| 141 | + |
| 142 | +const port = process.env.PORT || 5000; |
| 143 | + |
| 144 | +app.listen(port, () => { |
| 145 | + console.log('Listening on port ' + port); |
| 146 | +}); |
| 147 | + |
| 148 | +module.exports = app; |
0 commit comments