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

Commit 1a08469

Browse files
committed
further changes due to reviews
1 parent 8ebd49f commit 1a08469

File tree

10 files changed

+131
-190
lines changed

10 files changed

+131
-190
lines changed

CHANGELOG.md

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,3 @@
99
* Corrected README.md.
1010
* Added login with redirect.
1111
* Authentication decoupled from access token request.
12-
13-
## 3/06/2020

JavaScriptSPA/api.js

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
11
// helper function to access the resource with the token
22
function callApiWithAccessToken(endpoint, token) {
3-
const headers = new Headers();
4-
const bearer = `Bearer ${token}`;
5-
6-
headers.append("Authorization", bearer);
7-
8-
const options = {
9-
method: "GET",
10-
headers: headers
11-
};
3+
const headers = new Headers();
4+
const bearer = `Bearer ${token}`;
125

13-
fetch(endpoint, options)
14-
.then(response => response.json())
15-
.then(response => {
16-
logMessage("Web API returned:\n" + JSON.stringify(response));
17-
}).catch(error => {
18-
logMessage("Error calling the Web api:\n" + error);
19-
});
6+
headers.append("Authorization", bearer);
7+
8+
const options = {
9+
method: "GET",
10+
headers: headers
11+
};
12+
13+
fetch(endpoint, options)
14+
.then(response => response.json())
15+
.then(response => {
16+
logMessage("Web API returned:\n" + JSON.stringify(response));
17+
}).catch(error => {
18+
logMessage("Error calling the Web api:\n" + error);
19+
});
2020
}

JavaScriptSPA/apiConfig.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// The current application coordinates were pre-registered in a B2C tenant.
22
const apiConfig = {
3-
b2cScopes: ["https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read"],
4-
webApi: "https://fabrikamb2chello.azurewebsites.net/hello"
5-
};
3+
b2cScopes: ["https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read"],
4+
webApi: "https://fabrikamb2chello.azurewebsites.net/hello"
5+
};

JavaScriptSPA/authConfig.js

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,25 @@
1+
2+
// Config object to be passed to Msal on creation.
3+
// For a full list of msal.js configuration parameters,
4+
// visit https://azuread.github.io/microsoft-authentication-library-for-js/docs/msal/modules/_authenticationparameters_.html
15
const msalConfig = {
2-
auth: {
3-
clientId: "e760cab2-b9a1-4c0d-86fb-ff7084abd902",
4-
authority: "https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/b2c_1_susi",
5-
validateAuthority: false
6-
},
7-
cache: {
8-
cacheLocation: "localStorage",
9-
storeAuthStateInCookie: true
10-
}
6+
auth: {
7+
clientId: "e760cab2-b9a1-4c0d-86fb-ff7084abd902",
8+
authority: "https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/b2c_1_susi",
9+
validateAuthority: false
10+
},
11+
cache: {
12+
cacheLocation: "localStorage", // This configures where your cache will be stored
13+
storeAuthStateInCookie: true // Set this to "true" if you are having issues on IE11 or Edge
14+
}
1115
};
1216

13-
// request to sign-in (returns an idToken)
17+
// Add here scopes for id token to be used at the MS Identity Platform endpoints.
1418
const loginRequest = {
15-
scopes: ["openid", "profile"],
19+
scopes: ["openid", "profile"],
1620
};
1721

18-
// request to acquire a token for resource access
22+
// Add here scopes for access token to be used at the API endpoints.
1923
const tokenRequest = {
20-
scopes: apiConfig.b2cScopes
24+
scopes: ["https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read"]
2125
};

JavaScriptSPA/authPopup.js

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@ const myMSALObj = new Msal.UserAgentApplication(msalConfig);
44

55
function signIn() {
66
myMSALObj.loginPopup(loginRequest)
7-
.then(loginResponse => {
7+
.then(loginResponse => {
88
console.log('id_token acquired at: ' + new Date().toString());
9+
console.log(loginResponse);
910

1011
if (myMSALObj.getAccount()) {
1112
updateUI();
@@ -26,28 +27,28 @@ function getTokenPopup(request) {
2627
return myMSALObj.acquireTokenSilent(request)
2728
.catch(error => {
2829
console.log("silent token acquisition fails. acquiring token using popup");
29-
30+
console.log(error);
3031
// fallback to interaction when silent call fails
3132
return myMSALObj.acquireTokenPopup(request)
3233
.then(tokenResponse => {
3334
console.log('access_token acquired at: ' + new Date().toString());
34-
})
35-
.catch(error => {
35+
return tokenResponse;
36+
}).catch(error => {
3637
console.log(error);
3738
});
3839
});
3940
}
4041

41-
//calls the resource API with the token
42+
// Acquires and access token and then passes it to the API call
4243
function passTokenToApi() {
4344
getTokenPopup(tokenRequest)
44-
.then(tokenResponse => {
45-
console.log('access_token acquired at: ' + new Date().toString());
46-
try {
47-
logMessage("Request made to Web API:")
48-
callApiWithAccessToken(apiConfig.webApi, tokenResponse.accessToken);
49-
} catch(err) {
50-
console.log(err);
51-
}
52-
});
45+
.then(tokenResponse => {
46+
console.log('access_token acquired at: ' + new Date().toString());
47+
try {
48+
logMessage("Request made to Web API:")
49+
callApiWithAccessToken(apiConfig.webApi, tokenResponse.accessToken);
50+
} catch(err) {
51+
console.log(err);
52+
}
53+
});
5354
}

JavaScriptSPA/authRedirect.js

Lines changed: 31 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -8,59 +8,60 @@ let accessToken;
88
myMSALObj.handleRedirectCallback(authRedirectCallBack);
99

1010
function authRedirectCallBack(error, response) {
11-
if (error) {
12-
console.log(error);
11+
if (error) {
12+
console.log(error);
13+
} else {
14+
if (response.tokenType === "id_token") {
15+
console.log('id_token acquired at: ' + new Date().toString());
16+
myMSALObj.getAccount();
17+
getTokenRedirect(tokenRequest);
18+
} else if (response.tokenType === "access_token") {
19+
console.log('access_token acquired at: ' + new Date().toString());
20+
accessToken = response.accessToken;
21+
logMessage("Request made to Web API:")
22+
callApiWithAccessToken(apiConfig.webApi, accessToken)
1323
} else {
14-
if (response.tokenType === "id_token") {
15-
console.log('id_token acquired at: ' + new Date().toString());
16-
myMSALObj.getAccount();
17-
getTokenRedirect(tokenRequest);
18-
} else if (response.tokenType === "access_token") {
19-
console.log('access_token acquired at: ' + new Date().toString());
20-
accessToken = response.accessToken;
21-
logMessage("Request made to Web API:")
22-
callApiWithAccessToken(apiConfig.webApi, accessToken)
23-
} else {
24-
console.log("token type is:" + response.tokenType);
25-
}
24+
console.log("token type is:" + response.tokenType);
2625
}
26+
}
2727
}
2828

2929
// Redirect: once login is successful and redirects with tokens, update UI
3030
if (myMSALObj.getAccount()) {
31-
updateUI();
31+
updateUI();
3232
}
3333

3434
function signIn() {
35-
myMSALObj.loginRedirect(loginRequest)
35+
myMSALObj.loginRedirect(loginRequest)
3636
}
3737

3838

3939
// sign-out the user
4040
function logout() {
41-
// Removes all sessions, need to call AAD endpoint to do full logout
42-
myMSALObj.logout();
41+
// Removes all sessions, need to call AAD endpoint to do full logout
42+
myMSALObj.logout();
4343
}
4444

4545
// This function can be removed if you do not need to support IE
4646
function getTokenRedirect(request) {
4747
return myMSALObj.acquireTokenSilent(request)
48-
.then((response) => {
49-
if (response.accessToken) {
50-
accessToken = response.accessToken
51-
logMessage("Request made to Web API:")
52-
callApiWithAccessToken(apiConfig.webApi, accessToken)
53-
}
54-
}).catch(error => {
55-
console.log("silent token acquisition fails. acquiring token using redirect");
56-
// fallback to interaction when silent call fails
57-
return myMSALObj.acquireTokenRedirect(request)
58-
});
48+
.then((response) => {
49+
if (response.accessToken) {
50+
accessToken = response.accessToken
51+
logMessage("Request made to Web API:")
52+
callApiWithAccessToken(apiConfig.webApi, accessToken)
53+
}
54+
}).catch(error => {
55+
console.log("silent token acquisition fails. acquiring token using redirect");
56+
console.log(error);
57+
// fallback to interaction when silent call fails
58+
return myMSALObj.acquireTokenRedirect(request)
59+
});
5960
}
6061

6162

6263
// calls the resource API with the token
63-
function passTokenToAPI() {
64+
function passTokenToApi() {
6465
if (accessToken === null || accessToken === undefined) {
6566
getTokenRedirect(tokenRequest);
6667
} else {

JavaScriptSPA/index.html

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,12 @@
44
<meta charset="UTF-8">
55
<meta name="viewport" content="width=device-width, initial-scale=1.0">
66
<title>AAD B2C | MSAL.JS Vanilla JavaScript SPA</title>
7-
8-
<!-- bluebird only needed if this page needs to run on Internet Explorer -->
9-
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/bluebird@3.7.2/js/browser/bluebird.min.js"></script>
107

118
<!-- msal.min.js can be used in the place of msal.js; included msal.js to make debug easy -->
12-
<script type="text/javascript" src="https://alcdn.msftauth.net/lib/1.2.1/js/msal.js" integrity="sha384-9TV1245fz+BaI+VvCjMYL0YDMElLBwNS84v3mY57pXNOt6xcUYch2QLImaTahcOP" crossorigin="anonymous"></script>
13-
9+
<script type="text/javascript" src="https://alcdn.msauth.net/lib/1.2.1/js/msal.js" integrity="sha384-9TV1245fz+BaI+VvCjMYL0YDMElLBwNS84v3mY57pXNOt6xcUYch2QLImaTahcOP" crossorigin="anonymous"></script>
10+
<!-- msal.js with a fallback to backup CDN -->
1411
<script type="text/javascript">
15-
if(typeof Msal === 'undefined')document.write(unescape("%3Cscript src='https://alcdn.msftauth.net/lib/1.2.1/js/msal.js' type='text/javascript' integrity='sha384-9TV1245fz+BaI+VvCjMYL0YDMElLBwNS84v3mY57pXNOt6xcUYch2QLImaTahcOP' crossorigin='anonymous'%3E%3C/script%3E"));
12+
if(typeof Msal === 'undefined')document.write(unescape("%3Cscript src='https://alcdn.msftauth.net/lib/1.2.1/js/msal.js' type='text/javascript' integrity='sha384-m/3NDUcz4krpIIiHgpeO0O8uxSghb+lfBTngquAo2Zuy2fEF+YgFeP08PWFo5FiJ' crossorigin='anonymous'%3E%3C/script%3E"));
1613
</script>
1714

1815
<!-- adding Bootstrap 4 for UI components -->
@@ -26,7 +23,7 @@
2623
<a class="navbar-brand" href="/">Azure AD B2C</a>
2724
<div class="btn-group ml-auto dropleft">
2825
<button type="button" id="signIn" class="btn btn-secondary" onclick="signIn()">Sign In</button>
29-
<button type="button" id="signOut" class="btn btn-success" onclick="logout()" style="display:none">Sign Out</button>
26+
<button type="button" id="signOut" class="btn btn-success d-none" onclick="logout()">Sign Out</button>
3027
</div>
3128
</nav>
3229

@@ -36,7 +33,7 @@ <h5 class="card-header text-center">Getting an access token with Azure AD B2C an
3633
<div class="card-body text-center">
3734
<h5 id="label" class="card-title">Sign-in with Microsoft Azure AD B2C</h5>
3835
<pre id="response" class="card-text"></pre>
39-
<button type="button" id="callApiButton" class="btn btn-primary" onclick="callApi()" style="display:none">Call API</button>
36+
<button type="button" id="callApiButton" class="btn btn-primary d-none" onclick="passTokenToApi()">Call API</button>
4037
</div>
4138
</div>
4239

@@ -49,7 +46,9 @@ <h5 id="label" class="card-title">Sign-in with Microsoft Azure AD B2C</h5>
4946
<script type="text/javascript" src="./authConfig.js"></script>
5047
<script type="text/javascript" src="./apiConfig.js"></script>
5148
<script type="text/javascript" src="./ui.js"></script>
52-
<!-- replace next with authRedirect if you would like to use redirect flow -->
49+
50+
<!-- replace next line with authRedirect.js if you would like to use the redirect flow -->
51+
<!-- <script type="text/javascript" src="./authRedirect.js"></script> -->
5352
<script type="text/javascript" src="./authPopup.js"></script>
5453
<script type="text/javascript" src="./api.js"></script>
5554
</body>

JavaScriptSPA/ui.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,14 @@ function updateUI() {
1010
const userName = myMSALObj.getAccount().name;
1111
logMessage("User '" + userName + "' logged-in");
1212

13-
signInButton.style.display = 'none';
14-
signOutButton.style.display = 'initial';
13+
signInButton.classList.add('d-none');
14+
signOutButton.classList.remove('d-none');
1515

1616
// greet the user - specifying login
1717
label.innerText = "Hello " + userName;
1818

1919
// add the callWebApi button
20-
callWebApiButton.style.display = 'initial';
20+
callWebApiButton.classList.add('d-none');
2121
callWebApiButton.setAttribute('class', 'btn btn-primary');
2222
}
2323

0 commit comments

Comments
 (0)