This project illustrates a simple wrapper around MSAL Node to handle login, logout, and token acquisition. The wrapper is implemented in TypeScript and located under the src/ folder. The wrapper handles authentication with both Azure AD and Azure AD B2C.
- Start by installing the wrapper:
npm install- Once installed, build the project:
npm run build-
Then, initialize the wrapper in your app by providing a settings file in JSON. The file looks like the following:
{ "credentials": { "clientId": "CLIENT_ID", "tenantId": "TENANT_ID", "clientSecret": "CLIENT_SECRET" }, "settings": { "homePageRoute": "/home", "redirectUri": "http://localhost:4000/redirect", "postLogoutRedirectUri": "http://localhost:4000" } } -
Add the web API endpoints you would like to call under resources:
{ // ... "resources": { "graphAPI": { "callingPageRoute": "/profile", "endpoint": "https://graph.microsoft.com/v1.0/me", "scopes": ["user.read"] }, } } -
If you are authenticating with Azure AD B2C, user-flows and/or policies should be provided as well:
{
// ...
"policies": {
"signUpSignIn": {
"authority": "https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/B2C_1_susi"
},
}
}To initialize the wrapper, import it and supply the settings file and an (optional) persistent cache as below:
const settings = require('../../appSettings.json');
const cache = require('../utils/cachePlugin');
const msalWrapper = require('msal-express-wrapper');
const authProvider = new msalWrapper.AuthProvider(settings, cache);Once the wrapper is initialized, you can use it as below:
These routes are dedicated to the wrapper for handing authorization and token requests. They do not serve any page.
// authentication routes
app.get('/signin', authProvider.signIn);
app.get('/signout', authProvider.signOut);
app.get('/redirect', authProvider.handleRedirect);Simply add the isAuthenticated middleware before the controller that serves the page you would like to secure:
// secure routes
app.get('/id', authProvider.isAuthenticated, mainController.getIdPage);Simply add the getToken middleware before the controller that makes a call to the web API that you would like to access. The access token will be available as a session variable:
// secure routes that call protected resources
app.get('/profile', authProvider.isAuthenticated, authProvider.getToken, mainController.getProfilePage); // get token for this route to call web APISession support in this sample is provided by the express-session package. express-session is considered unfit for production, and you should either implement your own session solution or use a more suitable 3rd party library.
MSAL Node has an in-memory cache by default. This sample also features a persistent cache plugin in order to save the cache to disk. This plugin is not meant to be production-ready. As such, you might want to implement persistent caching using a 3rd party library like redis.