Skip to content
This repository was archived by the owner on Jun 25, 2023. It is now read-only.

Commit 28fce6e

Browse files
authored
Merge pull request #25 from Azure-Samples/dev
merge dev to main
2 parents 63c359a + 4165052 commit 28fce6e

103 files changed

Lines changed: 52701 additions & 16306 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

CONTRIBUTING.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Contributing to msal-express-wrapper
1+
# Contributing to microsoft-identity-express
22

33
This project welcomes contributions and suggestions. Most contributions require you to agree to a
44
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
@@ -51,12 +51,12 @@ chances of your issue being dealt with quickly:
5151
* **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be
5252
causing the problem (line of code or commit)
5353

54-
You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/Azure-Samples/msal-express-wrapper/issues/new.
54+
You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/Azure-Samples/microsoft-identity-express/issues/new.
5555

5656
### <a name="submit-pr"></a> Submitting a Pull Request (PR)
5757
Before you submit your Pull Request (PR) consider the following guidelines:
5858

59-
* Search the repository (https://github.com/Azure-Samples/msal-express-wrapper/pulls) for an open or closed PR
59+
* Search the repository (https://github.com/Azure-Samples/microsoft-identity-express/pulls) for an open or closed PR
6060
that relates to your submission. You don't want to duplicate effort.
6161

6262
* Make your changes in a new git fork:

README.md

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
---
99

10-
This project illustrates a simple wrapper around the [ConfidentialClientApplication](https://azuread.github.io/microsoft-authentication-library-for-js/ref/classes/_azure_msal_node.confidentialclientapplication.html) class of the [Microsoft Authentication Library for Node.js](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-node#microsoft-authentication-library-for-node-msal-node) (MSAL Node), in order to streamline routine authentication tasks such as login, logout and token acquisition, as well as securing routes and controlling access.
10+
This project illustrates a simple wrapper around the [ConfidentialClientApplication](https://azuread.github.io/microsoft-authentication-library-for-js/ref/classes/_azure_msal_node.confidentialclientapplication.html) class of the [Microsoft Authentication Library for Node.js](https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-node#microsoft-authentication-library-for-node-msal-node) (MSAL Node), in order to streamline routine authentication tasks such as login, logout and token acquisition, as well as securing routes and controlling access. In doing so it takes inspiration from the [Microsoft.Identity.Web](https://github.com/AzureAD/microsoft-identity-web) with respect to developer experience.
1111

1212
This is an open source project. [Suggestions](https://github.com/Azure-Samples/msal-express-wrapper/issues/new) and [contributions](https://github.com/Azure-Samples/msal-express-wrapper/blob/dev/CONTRIBUTING.md) are welcome!
1313

@@ -65,17 +65,18 @@ const appSettings = {
6565
clientSecret: "CLIENT_SECRET" // alt. client certificate or key vault credential
6666
},
6767
authRoutes: {
68-
redirect: "/redirect", // redirect URI configured on Azure AD
68+
redirect: "/redirect", // redirect path or the full URI configured on Azure AD
6969
error: "/error", // errors will be redirected to this route
7070
unauthorized: "/unauthorized" // unauthorized access attempts will be redirected to this route
71+
frontChannelLogout: "/sso_logout" // front-channel logout path or the full URI configured on Azure AD
7172
},
7273
remoteResources: {
7374
graphAPI: {
74-
endpoint: "https://graph.microsoft.com/v1.0/me", // Microsoft Graph
75+
endpoint: "https://graph.microsoft.com/v1.0/me", // Microsoft Graph API
7576
scopes: ["user.read"]
7677
},
7778
armAPI: {
78-
endpoint: "https://management.azure.com/tenants?api-version=2020-01-01", // Azure REST API
79+
endpoint: "https://management.azure.com/tenants?api-version=2020-01-01", // Azure Resource Manager REST API
7980
scopes: ["https://management.azure.com/user_impersonation"]
8081
}
8182
}
@@ -87,7 +88,7 @@ const appSettings = {
8788
```javascript
8889
const appSettings = {
8990
// ...
90-
policies: {
91+
b2cPolicies: {
9192
signUpSignIn: {
9293
authority: "https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/B2C_1_susi"
9394
}
@@ -102,7 +103,7 @@ Import the package and instantiate [AuthProvider](https://azure-samples.github.i
102103
```javascript
103104
const express = require('express');
104105
const session = require('express-session');
105-
const msalWrapper = require('msal-express-wrapper');
106+
const MsIdExpress = require('microsoft-identity-express');
106107

107108
const settings = require('./appSettings');
108109
const cache = require('./utils/cachePlugin');
@@ -121,11 +122,11 @@ app.use(session({
121122
}
122123
}));
123124

124-
const authProvider = new msalWrapper.AuthProvider(settings, cache);
125+
const msid = new MsIdExpress.WebAppAuthClientBuilder(appSettings).build();
125126

126-
app.use(authProvider.initialize()); // initialize default routes
127+
app.use(msid.initialize()); // initialize default routes
127128

128-
app.use(router(authProvider)); // use authProvider in routers downstream
129+
app.use(router(msid)); // use authProvider in routers downstream
129130

130131
app.listen(SERVER_PORT, () => console.log(`Server is listening on port ${SERVER_PORT}!`));
131132
```
@@ -134,7 +135,7 @@ The wrapper stores user data on `req.session` variable. Below are some of the us
134135

135136
* `req.session.isAuthenticated`: indicates if user is currently authenticated (*boolean*)
136137
* `req.session.account`: MSAL.js account object containing useful information like ID token claims (see [AccountInfo](https://azuread.github.io/microsoft-authentication-library-for-js/ref/modules/_azure_msal_common.html#accountinfo))
137-
* `req.session.remoteResources.{resourceName}`: Contains parameters related to an Azure AD / Azure AD B2C protected resource, including raw access tokens (see [Resource](https://azure-samples.github.io/msal-express-wrapper/docs/modules.html#resource))
138+
* `req.session.protectedResources.<resourceName>`: Contains parameters related to an Azure AD / Azure AD B2C protected resource, including raw access tokens (see [Resource](https://azure-samples.github.io/msal-express-wrapper/docs/modules.html#resource))
138139

139140
### Middleware
140141

@@ -147,7 +148,7 @@ const express = require('express');
147148
const appSettings = require('../appSettings');
148149
const mainController = require('../controllers/mainController');
149150

150-
module.exports = (authProvider) => {
151+
module.exports = (msid) => {
151152

152153
// initialize router
153154
const router = express.Router();
@@ -166,13 +167,13 @@ module.exports = (authProvider) => {
166167

167168
// auth routes
168169
router.get('/signin',
169-
authProvider.signIn({
170+
msid.signIn({
170171
successRedirect: "/",
171172
}),
172173
);
173174

174175
router.get('/signout',
175-
authProvider.signOut({
176+
msid.signOut({
176177
successRedirect: "/",
177178
}),
178179
);
@@ -190,7 +191,7 @@ Simply add the [isAuthenticated()](https://azure-samples.github.io/msal-express-
190191
```javascript
191192
// secure routes
192193
app.get('/id',
193-
authProvider.isAuthenticated({
194+
msid.isAuthenticated({
194195
unauthorizedRedirect: "/sign-in"
195196
}
196197
), // checks if authenticated via session
@@ -206,8 +207,8 @@ app.get('/id',
206207

207208
```javascript
208209
router.get('/profile',
209-
authProvider.isAuthenticated(),
210-
authProvider.getToken({
210+
msid.isAuthenticated(),
211+
msid.getToken({
211212
resource: {
212213
endpoint: "https://graph.microsoft.com/v1.0/me",
213214
scopes: [ "User.Read" ]
@@ -218,7 +219,7 @@ app.get('/id',
218219
// use axios or a similar alternative
219220
const response = await axios.default.get("https://graph.microsoft.com/v1.0/me", {
220221
headers: {
221-
Authorization: `Bearer ${accessToken}`
222+
Authorization: `Bearer ${req.session["graphAPI"].accessToken}`
222223
}
223224
});
224225

@@ -237,17 +238,15 @@ Use [hasAccess()](https://azure-samples.github.io/msal-express-wrapper/classes/a
237238

238239
```javascript
239240
router.use('/admin',
240-
authProvider.isAuthenticated(),
241-
authProvider.hasAccess({
241+
msid.isAuthenticated(),
242+
msid.hasAccess({
242243
accessRule: {
243244
methods: [ "GET", "POST", "DELETE" ],
244245
roles: [ "admin_role" ]
245246
}
246247
}),
247248
(req, res) => {
248-
const users = User.getAllUsers();
249-
250-
res.render('dashboard', { isAuthenticated: req.session.isAuthenticated, users: users });
249+
res.render('dashboard', { isAuthenticated: req.session.isAuthenticated });
251250
}
252251
);
253252
```

demo/App/app.js

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,9 @@ const express = require('express');
77
const session = require('express-session');
88
const path = require('path');
99

10-
const settings = require('./appSettings');
11-
const cache = require('./utils/cachePlugin');
10+
const MsIdExpress = require('../../dist/index');
11+
const appSettings = require('./appSettings');
1212

13-
const msalWrapper = require('../../dist/index');
1413
const router = require('./routes/router');
1514

1615
const SERVER_PORT = process.env.PORT || 4000;
@@ -33,31 +32,31 @@ async function main() {
3332
* Using express-session middleware. Be sure to familiarize yourself with available options
3433
* and set the desired options. Visit: https://www.npmjs.com/package/express-session
3534
*/
36-
const sessionConfig = {
35+
app.use(session({
3736
secret: 'ENTER_YOUR_SECRET_HERE',
3837
resave: false,
3938
saveUninitialized: false,
4039
cookie: {
41-
secure: false,
40+
secure: false,
4241
}
43-
}
44-
45-
if (app.get('env') === 'production') {
46-
app.set('trust proxy', 1) // trust first proxy
47-
sessionConfig.cookie.secure = true // serve secure cookies
48-
}
49-
50-
app.use(session(sessionConfig));
42+
}));
43+
44+
app.set('trust proxy', 1) // trust first proxy
5145

5246
try {
5347
// async building the wrapper as fetching credentials from key vault
54-
const authProvider = await msalWrapper.AuthProvider.buildAsync(settings, cache);
48+
const msid = await new MsIdExpress.WebAppAuthClientBuilder(appSettings)
49+
.withKeyVaultCredentials({
50+
credentialType: "clientSecret",
51+
credentialName: "WrapperExampleSecret",
52+
keyVaultUrl: "https://derisen-test-vault.vault.azure.net/"
53+
}).buildAsync();
5554

56-
app.use(authProvider.initialize());
57-
58-
app.use(router(authProvider));
59-
60-
app.listen(SERVER_PORT, () => console.log(`Server is listening on port ${SERVER_PORT}!`));
55+
app.use(msid.initialize());
56+
57+
app.use(router(msid));
58+
59+
app.listen(SERVER_PORT, () => console.log(`Server is listening on port ${SERVER_PORT}!`));
6160
} catch (error) {
6261
console.log(error);
6362
}

demo/App/appSettings.js

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,13 @@ const appSettings = {
22
appCredentials: {
33
clientId: "2a47e38d-600d-41c0-9d88-518326c9e4d7",
44
tenantId: "cbaf2168-de14-4c72-9d88-f5f05366dbef",
5-
keyVaultCredential: {
6-
credentialType: "secret",
7-
credentialName: "WrapperExampleSecret",
8-
keyVaultUrl: "https://derisen-test-vault.vault.azure.net/"
9-
}
105
},
116
authRoutes: {
127
redirect: "/redirect",
138
error: "/error",
149
unauthorized: "/unauthorized"
1510
},
16-
remoteResources: {
11+
protectedResources: {
1712
graphAPI: {
1813
endpoint: "https://graph.microsoft.com/v1.0/me",
1914
scopes: ["user.read"]

demo/App/controllers/mainController.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ exports.getProfilePage = async(req, res, next) => {
2020
let profile;
2121

2222
try {
23-
profile = await fetchManager.callAPI(appSettings.remoteResources.graphAPI.endpoint, req.session.remoteResources["graphAPI"].accessToken);
23+
profile = await fetchManager.callAPI(appSettings.protectedResources.graphAPI.endpoint, req.session.protectedResources["graphAPI"].accessToken);
2424
res.render('profile', { isAuthenticated: req.session.isAuthenticated, profile: profile });
2525
} catch (error) {
2626
console.log(error);
@@ -32,7 +32,7 @@ exports.getTenantPage = async(req, res, next) => {
3232
let tenant;
3333

3434
try {
35-
tenant = await fetchManager.callAPI(appSettings.remoteResources.armAPI.endpoint, req.session.remoteResources["armAPI"].accessToken);
35+
tenant = await fetchManager.callAPI(appSettings.protectedResources.armAPI.endpoint, req.session.protectedResources["armAPI"].accessToken);
3636
res.render('tenant', { isAuthenticated: req.session.isAuthenticated, tenant: tenant.value[0] });
3737
} catch (error) {
3838
console.log(error);

demo/App/data/cache.json

Whitespace-only changes.

demo/App/routes/router.js

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
const express = require('express');
22
const mainController = require('../controllers/mainController');
33

4-
module.exports = (authProvider) => {
4+
module.exports = (msid) => {
55

66
// initialize router
77
const router = express.Router();
@@ -12,35 +12,36 @@ module.exports = (authProvider) => {
1212

1313
// auth routes
1414
router.get('/signin',
15-
authProvider.signIn({
16-
successRedirect: "/",
15+
msid.signIn({
16+
postLoginRedirect: "/",
17+
failureRedirect: "/signin"
1718
}),
1819
);
1920

2021
router.get('/signout',
21-
authProvider.signOut({
22-
successRedirect: "/",
22+
msid.signOut({
23+
postLogoutRedirect: "/",
2324
}),
2425
);
2526

2627
// secure routes
2728
router.get('/id',
28-
authProvider.isAuthenticated(),
29+
msid.isAuthenticated(),
2930
mainController.getIdPage
3031
);
3132

3233
router.get('/profile',
33-
authProvider.isAuthenticated(),
34-
authProvider.getToken({
35-
resource: authProvider.appSettings.remoteResources.graphAPI
34+
msid.isAuthenticated(),
35+
msid.getToken({
36+
resource: msid.appSettings.protectedResources.graphAPI
3637
}),
3738
mainController.getProfilePage
3839
); // get token for this route to call web API
3940

4041
router.get('/tenant',
41-
authProvider.isAuthenticated(),
42-
authProvider.getToken({
43-
resource: authProvider.appSettings.remoteResources.armAPI
42+
msid.isAuthenticated(),
43+
msid.getToken({
44+
resource: msid.appSettings.protectedResources.armAPI
4445
}),
4546
mainController.getTenantPage
4647
); // get token for this route to call web API

demo/App/utils/cachePlugin.js

Lines changed: 0 additions & 38 deletions
This file was deleted.

demo/README.md

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ This sample demonstrates a Node.js & Express web application that authenticates
1515
| `App/app.js` | Application entry point. |
1616
| `App/appSettings.json` | Application settings and authentication parameters. |
1717
| `App/routes/router.js` | Application routes are defined here. |
18-
| `App/utils/cachePlugin.js` | Example cache plugin implementation for saving cache to disk. |
1918

2019
## Prerequisites
2120

@@ -71,12 +70,9 @@ Open the project in your IDE (like Visual Studio or Visual Studio Code) to confi
7170
> In the steps below, "ClientID" is the same as "Application ID" or "AppId".
7271
7372
1. Open the `./App/appSettings.json` file.
74-
1. Find the key `clientId` and replace the existing value with the **application ID** (clientId) of the `ExpressWebApp` application copied from the Azure Portal.
75-
1. Find the key `tenantId` and replace the existing value with your Azure AD **tenant ID**.
76-
1. Find the key `clientSecret` and replace the existing value with the key you saved during the creation of the `ExpressWebApp` app, in the Azure Portal.
77-
1. Find the key `homePageRoute` and replace the existing value with the route that you wish to be redirected after sign-in, e.g. `/home`.
78-
1. Find the key `redirectUri` and replace the existing value with the **Redirect URI** for `ExpressWebApp` app. For example, `http://localhost:4000/redirect`.
79-
1. Find the `postLogoutRedirectUri` and replace the existing value with the URI that you wish to be redirected after sign-out, e.g. `http://localhost:4000/`
73+
1. Find the key `appCredentials.clientId` and replace the existing value with the **application ID** (clientId) of the `ExpressWebApp` application copied from the Azure Portal.
74+
1. Find the key `appCredentials.tenantInfo` and replace the existing value with your Azure AD **tenant ID** (alternatively, `common` for all audiences).
75+
1. Find the key `authRoutes.redirect` and replace the existing value with the **Redirect URI** for `ExpressWebApp` app. For example, `http://localhost:4000/redirect` or simply `/redirect`.
8076

8177
## Running the sample
8278

0 commit comments

Comments
 (0)