Skip to content
This repository has been archived by the owner. It is now read-only.

Commit c45e34b

Browse files
committed
review requests
1 parent 24e5cf4 commit c45e34b

File tree

10 files changed

+165
-139
lines changed

10 files changed

+165
-139
lines changed

JavaScriptSPA/api.js

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// helper function to access the resource with the token
2-
function callApiWithAccessToken(endpoint, accessToken) {
2+
function callApiWithAccessToken(endpoint, token) {
33
const headers = new Headers();
4-
const bearer = `Bearer ${accessToken}`;
4+
const bearer = `Bearer ${token}`;
55

66
headers.append("Authorization", bearer);
77

@@ -32,4 +32,14 @@ function callApi() {
3232
console.log(err);
3333
}
3434
});
35-
}
35+
}
36+
37+
// calls the resource API with the token
38+
// use this instead if you're doing redirect flow
39+
// function callApi() {
40+
// if (accessToken === null || accessToken === undefined) {
41+
// getTokenRedirect(tokenRequest);
42+
// } else {
43+
// callApiWithAccessToken(apiConfig.webApi, accessToken)
44+
// }
45+
// }

JavaScriptSPA/auth.js

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

JavaScriptSPA/authConfig.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
const msalConfig = {
22
auth: {
33
clientId: "e760cab2-b9a1-4c0d-86fb-ff7084abd902", //This is your client ID
4-
authority: "https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/b2c_1_susi", //This is your tenant info
4+
authority: "https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/" + b2cPolicies.signUpSignIn, //This is your tenant info
55
validateAuthority: false
66
},
77
cache: {

JavaScriptSPA/authPopup.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Create the main myMSALObj instance
2+
// configuration parameters are located at authConfig.js
3+
const myMSALObj = new Msal.UserAgentApplication(msalConfig);
4+
5+
function signIn() {
6+
myMSALObj.loginPopup(loginRequest)
7+
.then(loginResponse => {
8+
console.log(loginResponse);
9+
console.log('id_token acquired at: ' + new Date().toString());
10+
11+
if (myMSALObj.getAccount()) {
12+
updateUI();
13+
}
14+
15+
}).catch(function (error) {
16+
console.log(error);
17+
});
18+
}
19+
20+
// sign-out the user
21+
function logout() {
22+
// Removes all sessions, need to call AAD endpoint to do full logout
23+
myMSALObj.logout();
24+
}
25+
26+
function getTokenPopup(request) {
27+
return myMSALObj.acquireTokenSilent(request)
28+
.catch(error => {
29+
console.log("silent token acquisition fails. acquiring token using popup");
30+
31+
// fallback to interaction when silent call fails
32+
return myMSALObj.acquireTokenPopup(request)
33+
.then(tokenResponse => {
34+
35+
}).catch(error => {
36+
console.log(error);
37+
});
38+
});
39+
}

JavaScriptSPA/authRedirect.js

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
2+
"use strict";
3+
4+
// Create the main myMSALObj instance
5+
// configuration parameters are located at authConfig.js
6+
const myMSALObj = new Msal.UserAgentApplication(msalConfig);
7+
8+
// Register Callbacks for Redirect flow
9+
myMSALObj.handleRedirectCallback(authRedirectCallBack);
10+
11+
function authRedirectCallBack(error, response) {
12+
if (error) {
13+
console.log(error);
14+
} else {
15+
if (response.tokenType === "id_token" && myMSALObj.getAccount() && !myMSALObj.isCallback(window.location.hash)) {
16+
console.log('id_token acquired at: ' + new Date().toString());
17+
updateUI();
18+
getTokenRedirect(tokenRequest);
19+
} else if (response.tokenType === "access_token") {
20+
console.log('access_token acquired at: ' + new Date().toString());
21+
} else {
22+
console.log("token type is:" + response.tokenType);
23+
}
24+
}
25+
}
26+
27+
// Redirect: once login is successful and redirects with tokens, update UI
28+
if (myMSALObj.getAccount() && !myMSALObj.isCallback(window.location.hash)) {
29+
// avoid duplicate code execution on page load in case of iframe and Popup window.
30+
updateUI();
31+
}
32+
33+
34+
function signIn() {
35+
myMSALObj.loginRedirect(loginRequest)
36+
}
37+
38+
39+
// sign-out the user
40+
function logout() {
41+
// Removes all sessions, need to call AAD endpoint to do full logout
42+
myMSALObj.logout();
43+
}
44+
45+
// This function can be removed if you do not need to support IE
46+
function getTokenRedirect(request) {
47+
return myMSALObj.acquireTokenSilent(request)
48+
.then((response) => {
49+
if (response.accessToken) {
50+
accessToken = response.accessToken
51+
}
52+
}).catch(error => {
53+
console.log("silent token acquisition fails. acquiring token using redirect");
54+
// fallback to interaction when silent call fails
55+
return myMSALObj.acquireTokenRedirect(request)
56+
});
57+
}

JavaScriptSPA/index.html

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,21 +23,15 @@
2323
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
2424
<a class="navbar-brand" href="/">Azure AD B2C</a>
2525
<div class="btn-group ml-auto dropleft">
26-
<button type="button" id="SignIn" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
27-
Sign In
28-
</button>
29-
<div class="dropdown-menu">
30-
<button class="dropdown-item" id="Popup" onclick="signIn(this.id)">Sign in using Popup</button>
31-
<button class="dropdown-item" id="Redirect" onclick="signIn(this.id)">Sign in using Redirect</button>
32-
</div>
26+
<button type="button" id="SignIn" class="btn btn-secondary">Sign In</button>
3327
</div>
3428
</nav>
3529
<div class="card">
3630
<h5 class="card-header text-center">Getting an access token with Azure AD B2C and calling a Web API</h5>
3731
<div class="card-body text-center">
3832
<h5 id="label" class="card-title">Sign-in with Microsoft Azure AD B2C</h5>
3933
<pre id="response" class="card-text"></pre>
40-
<button type="button" id="callApiButton" class="btn btn-primary" style="display:none" onclick="callApi()">Call API</button>
34+
<button type="button" id="callApiButton" class="btn btn-primary" style="display:none">Call API</button>
4135
</div>
4236
</div>
4337

@@ -47,10 +41,11 @@ <h5 id="label" class="card-title">Sign-in with Microsoft Azure AD B2C</h5>
4741
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
4842

4943
<!-- importing app scripts -->
44+
<script type="text/javascript" src="./poliConfig.js"></script>
5045
<script type="text/javascript" src="./authConfig.js"></script>
5146
<script type="text/javascript" src="./apiConfig.js"></script>
47+
<script type="text/javascript" src="./authPopup.js"></script>
5248
<script type="text/javascript" src="./ui.js"></script>
53-
<script type="text/javascript" src="./auth.js"></script>
5449
<script type="text/javascript" src="./api.js"></script>
5550
</body>
5651
</html>

JavaScriptSPA/poliConfig.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
2+
// add here b2c policies you have
3+
const b2cPolicies = {
4+
signUpSignIn: "b2c_1_susi",
5+
}

JavaScriptSPA/ui.js

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,33 @@
1-
// updates the UI post login/token acquisition
2-
function updateUI() {
3-
const userName = myMSALObj.getAccount().name;
4-
logMessage("User '" + userName + "' logged-in");
1+
// UI elements to work with
2+
const signInButton = document.getElementById('SignIn');
3+
signInButton.addEventListener('click', signIn);
54

6-
// add the logout button
7-
const signInButton = document.getElementById('SignIn');
8-
signInButton.nextElementSibling.style.display = 'none';
9-
signInButton.innerHTML = 'logout';
10-
signInButton.setAttribute('onclick', 'logout();');
11-
signInButton.setAttribute('class', "btn btn-success ml-auto")
5+
const callWebApiButton = document.getElementById('callApiButton');
126

13-
// greet the user - specifying login
14-
const label = document.getElementById('label');
15-
label.innerText = "Hello " + userName;
7+
const label = document.getElementById('label');
8+
const response = document.getElementById("response");
169

17-
// add the callWebApi button
18-
const callWebApiButton = document.getElementById('callApiButton');
19-
callWebApiButton.style.display = 'initial';
20-
callWebApiButton.setAttribute('class', 'btn btn-primary');
10+
// updates the UI post login/token acquisition
11+
function updateUI() {
12+
const userName = myMSALObj.getAccount().name;
13+
logMessage("User '" + userName + "' logged-in");
14+
15+
// add the logout button
16+
signInButton.innerHTML = 'logout';
17+
signInButton.setAttribute('class', "btn btn-success ml-auto")
18+
signInButton.removeEventListener('click', signIn);
19+
signInButton.addEventListener('click', logout);
20+
21+
// greet the user - specifying login
22+
label.innerText = "Hello " + userName;
23+
24+
// add the callWebApi button
25+
callWebApiButton.style.display = 'initial';
26+
callWebApiButton.setAttribute('class', 'btn btn-primary');
27+
callWebApiButton.addEventListener('click', callApi);
2128
}
2229

2330
// debug helper
2431
function logMessage(s) {
25-
document.getElementById("response")
26-
.appendChild(document.createTextNode('\n' + s));
32+
response.appendChild(document.createTextNode('\n' + s));
2733
}

README.md

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ From your shell or command line:
4242
```bash
4343
cd active-directory-b2c-javascript-msal-singlepageapp
4444
npm install && npm update
45-
node server.js
45+
npm start
4646
```
4747

4848
The console window shows the port number for the web application
@@ -139,12 +139,14 @@ Provide the following values for the Single Page Application registration:
139139

140140
Now in the sample code, you can replace the single-page application's demo environment configuration with your own tenant.
141141

142-
1. Open the `authConfig.js` file.
143-
2. Find the assignment for `clientID` and replace the value with the Application ID for the single page application you registered in Step 4, for example the Application ID found in `My Test SPA` application in the Azure portal.
144-
3. Find the assignment for `authority` and replacing `b2c_1_susi` with the name of the policy you created in Step 2, and `fabrikamb2c.onmicrosoft.com` by the name of your Azure AD B2C tenant, for example `https://<your-tenant-name>.b2clogin.com/<your-tenant-name>.onmicrosoft.com/<your-sign-in-sign-up-policy>`
145-
4. Open the `apiConfig.js` file.
146-
5. Find the assignment for the scopes `b2cScopes` replacing the URL by the scope URL you created for the Web API, e.g. `b2cScopes: ["https://<your-tenant-name>.onmicrosoft.com/helloapi/demo.read"]`
147-
6. Find the assignment for API URL `webApi` replacing the current URL by the URL where you deployed your Web API in Step 4, e.g. `webApi: "https://fabrikamb2chello.azurewebsites.net/hello`
142+
1. Open the `poliConfig.js` file.
143+
2. In the `b2cPolicies` object, replace the current signUp-signIn policy value with the name of the policy you created in Step 2 (if you have additional policies, you can add them here as well).
144+
3. Open the `authConfig.js` file.
145+
4. Find the assignment for `clientID` and replace the value with the Application ID for the single page application you registered in Step 4, for example the Application ID found in `My Test SPA` application in the Azure portal.
146+
5. Find the assignment for `authority` and replace `fabrikamb2c.onmicrosoft.com` by the name of your Azure AD B2C tenant, for example `https://<your-tenant-name>.b2clogin.com/<your-tenant-name>.onmicrosoft.com/<your-sign-in-sign-up-policy>`
147+
6. Open the `apiConfig.js` file.
148+
7. Find the assignment for the scopes `b2cScopes` replacing the URL by the scope URL you created for the Web API, e.g. `b2cScopes: ["https://<your-tenant-name>.onmicrosoft.com/helloapi/demo.read"]`
149+
8. Find the assignment for API URL `webApi` replacing the current URL by the URL where you deployed your Web API in Step 4, e.g. `webApi: "https://fabrikamb2chello.azurewebsites.net/hello`
148150

149151
Your resulting code should look as follows:
150152

@@ -167,8 +169,8 @@ const tokenRequest = {
167169
```javascript
168170
const msalConfig = {
169171
auth: {
170-
clientId: "e760cab2-b9a1-4c0d-86fb-ff7084abd902", //This is your client ID
171-
authority: "https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/b2c_1_susi", //This is your tenant info
172+
clientId: "e760cab2-b9a1-4c0d-86fb-ff7084abd902",
173+
authority: "https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/" + b2cPolicies.signUpSignIn,
172174
validateAuthority: false
173175
},
174176
cache: {
@@ -178,6 +180,12 @@ const msalConfig = {
178180
};
179181
```
180182

183+
```javascript
184+
const b2cPolicies = {
185+
signUpSignIn: "b2c_1_susi",
186+
}
187+
```
188+
181189
### Step 7: Run the sample
182190

183191
1. Install the node dependencies if this is your first time running the app (e.g. if you skipped running in the demo environment):

0 commit comments

Comments
 (0)