Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IE11 Auth Code Sample #1883

Merged
merged 15 commits into from
Jul 6, 2020
75 changes: 75 additions & 0 deletions samples/msal-browser-samples/VanillaJSTestApp2.0/app/IE11/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Browser check variables
// If you support IE, our recommendation is that you sign-in using Redirect APIs
// If you as a developer are testing using Edge InPrivate mode, please add "isEdge" to the if check
const ua = window.navigator.userAgent;
const msie = ua.indexOf("MSIE ");
const msie11 = ua.indexOf("Trident/");
const msedge = ua.indexOf("Edge/");
const isIE = msie > 0 || msie11 > 0;
const isEdge = msedge > 0;

let username = "";

// Create the main myMSALObj instance
// configuration parameters are located at authConfig.js
const myMSALObj = new msal.PublicClientApplication(msalConfig);

// Redirect: once login is successful and redirects with tokens, call Graph API
myMSALObj.handleRedirectPromise().then(handleResponse).catch(function (err) {
console.error(err);
});

function handleResponse(resp) {
if (resp !== null) {
username = resp.account.username;
showWelcomeMessage();

if (resp.accessToken) {
callMSGraph(graphConfig.graphMeEndpoint, resp.accessToken, updateUI);
profileButton.style.display = 'none';
}
} else {
// need to call getAccount here?
const currentAccounts = myMSALObj.getAllAccounts();
if (currentAccounts === null) {
return;
} else if (currentAccounts.length > 1) {
// Add choose account code here
} else if (currentAccounts.length === 1) {
username = currentAccounts[0].username;
console.log(username)
showWelcomeMessage();
}
}
}

function signIn() {
myMSALObj.loginRedirect(request)
}

function signOut() {
const logoutRequest = {
account: myMSALObj.getAccountByUsername(username)
};

myMSALObj.logout(logoutRequest);
}

function getTokenRedirect(request, account) {
request.account = account;
return new Promise(function(resolve, reject) {
myMSALObj.acquireTokenSilent(request).then(function (response) {
resolve(response)
}).catch(function (error) {
console.log("silent token acquisition fails.");
if (error instanceof msal.InteractionRequiredAuthError) {
// fallback to interaction when silent call fails
console.log("acquiring token using redirect");
myMSALObj.acquireTokenRedirect(request);
} else {
console.error(error);
reject(error);
}
});
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Config object to be passed to Msal on creation
const msalConfig = {
auth: {
clientId: "3fba556e-5d4a-48e3-8e1a-fd57c12cb82e",
authority: "https://login.windows-ppe.net/common/"
},
cache: {
cacheLocation: "localStorage", // This configures where your cache will be stored
storeAuthStateInCookie: true, // Set this to "true" if you are having issues on IE11 or Edge
tnorling marked this conversation as resolved.
Show resolved Hide resolved
}
};

// Add here scopes for id token to be used at MS Identity Platform endpoints.
const request = {
scopes: ["User.Read"]
};

// Add here the endpoints for MS Graph API services you would like to use.
const graphConfig = {
graphMeEndpoint: "https://graph.microsoft-ppe.com/v1.0/me"
};
28 changes: 28 additions & 0 deletions samples/msal-browser-samples/VanillaJSTestApp2.0/app/IE11/graph.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Helper function to call MS Graph API endpoint
// using authorization bearer token scheme
function callMSGraph(endpoint, accessToken, callback) {
const bearer = "Bearer " + accessToken;

var xmlHTTP = new XMLHttpRequest();
xmlHTTP.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
callback(JSON.parse(this.responseText));
}
}
xmlHTTP.open("GET", endpoint, true);
xmlHTTP.setRequestHeader('Authorization', bearer)
xmlHTTP.send();
}

function seeProfileRedirect() {
const currentAcc = myMSALObj.getAccountByUsername(username);
tnorling marked this conversation as resolved.
Show resolved Hide resolved
if (currentAcc) {
getTokenRedirect(request, currentAcc).then(function (response) {
// Will only execute if token was acquired silently
callMSGraph(graphConfig.graphMeEndpoint, response.accessToken, updateUI);
profileButton.style.display = 'none';
}).catch(function (error) {
console.log(error);
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>Quickstart | MSAL.JS Vanilla JavaScript SPA (IE11 Sample)</title>

<!-- IE support: add promises polyfill before msal.js -->
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/bluebird@3.7.2/js/browser/bluebird.min.js"></script>
tnorling marked this conversation as resolved.
Show resolved Hide resolved
<script src="../../lib/msal-browser.js"></script>

<!-- adding Bootstrap 4 for UI components -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="SHORTCUT ICON" href="https://c.s-microsoft.com/favicon.ico?v2" type="image/x-icon">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="/">MS Identity Platform</a>
<div class="btn-group ml-auto dropleft">
<button id="SignIn" class="btn btn-secondary" onclick="signIn()">Sign in</button>
</div>
</nav>
<br>
<h5 class="card-header text-center">Vanilla JavaScript SPA calling MS Graph API with MSAL.JS (IE11 Sample)</h5>
<br>
<div class="row" style="margin:auto" >
<div id="card-div" class="col-md-3" style="display:none">
<div class="card text-center">
<div class="card-body">
<h5 class="card-title" id="WelcomeMessage">Please sign-in to see your profile and read your mails</h5>
<div id="profile-div"></div>
<br>
<br>
<button class="btn btn-primary" id="seeProfile" onclick="seeProfileRedirect()">See Profile</button>
</div>
</div>
</div>
<br>
<br>
<div class="col-md-4">
<div class="list-group" id="list-tab" role="tablist">
</div>
</div>
<div class="col-md-5">
<div class="tab-content" id="nav-tabContent">
</div>
</div>
</div>
<br>
<br>

<!-- importing bootstrap.js and supporting js libraries -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

<!-- importing app scripts | load order is important -->
<script type="text/javascript" src="./authConfig.js"></script>
<script type="text/javascript" src="./ui.js"></script>
<script type="text/javascript" src="./auth.js"></script>
<script type="text/javascript" src="./graph.js"></script>
</body>
</html>
33 changes: 33 additions & 0 deletions samples/msal-browser-samples/VanillaJSTestApp2.0/app/IE11/ui.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Select DOM elements to work with
const welcomeDiv = document.getElementById("WelcomeMessage");
const signInButton = document.getElementById("SignIn");
const cardDiv = document.getElementById("card-div");
const mailButton = document.getElementById("readMail");
const profileButton = document.getElementById("seeProfile");
const profileDiv = document.getElementById("profile-div");

function showWelcomeMessage() {
// Reconfiguring DOM elements
cardDiv.setAttribute('style', 'display:initial');
welcomeDiv.innerHTML = 'Welcome ' + username;
signInButton.setAttribute("onclick", "signOut();");
signInButton.setAttribute('class', "btn btn-success")
signInButton.innerHTML = "Sign Out";
}

function updateUI(data) {
console.log('Graph API responded at: ' + new Date().toString());

const title = document.createElement('p');
title.innerHTML = "<strong>Title: </strong>" + data.jobTitle;
const email = document.createElement('p');
email.innerHTML = "<strong>Mail: </strong>" + data.mail;
const phone = document.createElement('p');
phone.innerHTML = "<strong>Phone: </strong>" + data.businessPhones[0];
const address = document.createElement('p');
address.innerHTML = "<strong>Location: </strong>" + data.officeLocation;
profileDiv.appendChild(title);
profileDiv.appendChild(email);
profileDiv.appendChild(phone);
profileDiv.appendChild(address);
}