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

Commit

Permalink
Working sample.
Browse files Browse the repository at this point in the history
The sample works with local accounts (use the sign-up now link at the bottom of the sign-in popup dialog), or gmail account.
It does not work yet with Microsoft personal accounts (MSA) and Twitter accounts.
  • Loading branch information
jmprieur committed May 10, 2017
1 parent 4953017 commit 1bc9127
Show file tree
Hide file tree
Showing 5 changed files with 110 additions and 2,480 deletions.
145 changes: 69 additions & 76 deletions index.html
@@ -1,6 +1,6 @@
<html>
<head>
<title>authentication with Msal.js app</title>
<title>Calling a Web API as a user authenticated with Msal.js app</title>
<style>
.hidden {
visibility: hidden
Expand All @@ -9,118 +9,111 @@
.visible {
visibility: visible
}

.response {
border: solid;
border-width: thin;
background-color: azure;
padding: 2px;
}
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>
<script src="public/msal.js" class="pre"></script>
<!-- bluebird only needed if this page needs to run on Internet Explorer -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js" class="pre"></script>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/0.1.1/js/msal.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" class="pre"></script>
<h1>Accessing a Web API with msal.js and AAD/B2C</h1>

<h2>Getting an access token with Azure AD B2C and calling a Web API</h2>
<div>
<div id="label">Sign-in with Microsoft</div>
<button id="auth" onclick="login();">Login</button>
</div>
<div id="callApi" class="hidden">
<button id="auth" onclick="callApi();">Call Web API</button>
<div id="label">Sign-in with Microsoft Azure AD B2C</div>
<button id="auth" onclick="login()">Login</button>
<button id="callApiButton" class="hidden" onclick="callApi()">Call Web API</button>
</div>

<pre class="response"></pre>

<script class="pre">

"use strict";
// The current application coordinates were pre-registered in a B2C tenant.
var applicationConfig = {
tenantID: 'fabrikamb2c.onmicrosoft.com', // Tenant in which the AAD-B2C directory was created "something.onmicrosoft.com""
clientID: 'e760cab2-b9a1-4c0d-86fb-ff7084abd902', // ClientID of the application as registered in the AAD-B2C tenant.
policyName: 'b2c_1_susi', // Name of a sign-in sign-up policy added to the AAD-B2C tenant
redirectUri: 'http://localhost:6420/', // Redirect URL for the application. Needs also to be added in the application's properties in B2C
webApi: 'https://fabrikamb2chello.azurewebsites.net/hello', // Web API to call
scopes: ['https://fabrikamb2c.onmicrosoft.com/demoapi/demo.read'] // Scope required to access the WebAPI
clientID: 'e760cab2-b9a1-4c0d-86fb-ff7084abd902',
authority: "https://login.microsoftonline.com/tfp/fabrikamb2c.onmicrosoft.com/b2c_1_susi",
b2cScopes: ["https://fabrikamb2c.onmicrosoft.com/demoapi/demo.read"],
webApi: 'https://fabrikamb2chello.azurewebsites.net/hello',
};

// authority in the form: "https://login.microsoftonline.com/tfp/<B2C-TenantId>/<B2C-policyName>",
var authority = "https://login.microsoftonline.com/tfp/" + applicationConfig.tenantID + "/" + applicationConfig.policyName;

</script>

<script>
"use strict";
var clientApplication = new Msal.UserAgentApplication(applicationConfig.clientID, authority, authenticationCallback);
clientApplication.redirectUri = applicationConfig.redirectUri;
var clientApplication = new Msal.UserAgentApplication(applicationConfig.clientID, applicationConfig.authority, function (errorDesc, token, error, tokenType) {
// Called after loginRedirect or acquireTokenPopup
});

// The authentication callback is needed when we use loginRedirect, acquireTokenRedirect
function authenticationCallback(errorDesc, token, error, tokenType) {
//This function is called after loginRedirect. msal object is bound to the window object after the constructor is called.
if (token) {
}
else {
logMessage(error + ":" + errorDesc);
}
function login() {
clientApplication.loginPopup(applicationConfig.b2cScopes).then(function (idToken) {
clientApplication.acquireTokenSilent(applicationConfig.b2cScopes).then(function (accessToken) {
updateUI();
}, function (error) {
clientApplication.acquireTokenPopup(applicationConfig.b2cScopes).then(function (accessToken) {
updateUI();
}, function (error) {
logMessage("Error acquiring the popup:\n" + error);
});
})
}, function (error) {
logMessage("Error during login:\n" + error);
});
}

function onAuthentication(idToken) {
// Change button to Sign Out
function updateUI() {
var userName = clientApplication.getUser().name;
logMessage("User '" + userName + "' logged-in");
var authButton = document.getElementById('auth');
authButton.innerHTML = 'logout';
authButton.setAttribute('onclick', 'logout();');
var label = document.getElementById('label');
label.innerText = "Hello " + clientApplication.getUser().name + "! Please press callApi to call the Api";

// Show the email address part
var callApiSpan = document.getElementById('callApi');
callApiSpan.className = "visible";
label.innerText = "Hello " + userName;
var callWebApiButton = document.getElementById('callApiButton');
callWebApiButton.setAttribute('class', 'visible');
}

function login() {
clientApplication.loginPopup(applicationConfig.scopes)
.then(onAuthentication, logMessage);
function callApi() {
clientApplication.acquireTokenSilent(applicationConfig.b2cScopes).then(function (accessToken) {
callApiWithAccessToken(accessToken);
}, function (error) {
clientApplication.acquireTokenPopup(applicationConfig.b2cScopes).then(function (accessToken) {
callApiWithAccessToken(accessToken);
}, function (error) {
logMessage("Error acquiring the access token to call the Web api:\n" + error);
});
})
}

function callWebApi(accessToken) {
logMessage("Calling the web API");
function callApiWithAccessToken(accessToken) {
// Call the Web API with the AccessToken
$.ajax({
type: "POST",
contentType: "application/json",
dataType: 'json',
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'bearer ' + accessToken);
},
type: "GET",
url: applicationConfig.webApi,
data: JSON.stringify({}),
processData: false,
success: function (msg) {
logMessage(msg);
}
});
headers: {
'Authorization': 'Bearer ' + accessToken,
},
}).done(function (data) {
logMessage("Web APi returned:\n" + JSON.stringify(data));
})
.fail(function (jqXHR, textStatus) {
logMessage("Error calling the Web api:\n" + textStatus);
})
}

function logout() {
// Removes all sessions, need to call AAD endpoint to do full logout
clientApplication.logout();
}

/*
function callApi() {
clientApplication.acquireTokenSilent(applicationConfig.scopes)
.then(callWebApi, function (error) {
return clientApplication.acquireTokenPopup(applicationConfig.scopes)
})
.then(callWebApi, logMessage);
}*/

function callApi() {
clientApplication.acquireTokenSilent(applicationConfig.scopes)
.then(function (accessToken) {
logMessage(accessToken)
}, function (error) {
logMessage(accessToken)
});
}


function logMessage(s) {
document.body.querySelector('.response').appendChild(document.createTextNode("\n\n" + JSON.stringify(s, true, 2)));
document.body.querySelector('.response').appendChild(document.createTextNode('\n' + s));
}

</script>
</body>
</html>
</html>
11 changes: 11 additions & 0 deletions package.json
@@ -0,0 +1,11 @@
{
"name": "msal-js-devapp-b2c",
"version": "1.1.0",
"license": "MIT",
"main": "server.js",
"dependencies": {
"express": "^4.12.3",
"morgan": "^1.5.2",
"path": "^0.11.14"
}
}

0 comments on commit 1bc9127

Please sign in to comment.