Instantly share code, notes, and snippets.
Last active
December 13, 2019 21:34
-
Star
(0)
0
You must be signed in to star a gist -
Fork
(0)
0
You must be signed in to fork a gist
-
Save jpda/64e21f3c5b91c0b92c00535b597a0c79 to your computer and use it in GitHub Desktop.
silent teams tab auth with graph scopes & adal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- | |
// Copyright (c) Microsoft Corporation | |
// All rights reserved. | |
// | |
// MIT License: | |
// Permission is hereby granted, free of charge, to any person obtaining | |
// a copy of this software and associated documentation files (the | |
// "Software"), to deal in the Software without restriction, including | |
// without limitation the rights to use, copy, modify, merge, publish, | |
// distribute, sublicense, and/or sell copies of the Software, and to | |
// permit persons to whom the Software is furnished to do so, subject to | |
// the following conditions: | |
// | |
// The above copyright notice and this permission notice shall be | |
// included in all copies or substantial portions of the Software. | |
// | |
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, | |
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | |
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE | |
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | |
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION | |
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
--> | |
<html> | |
<head> | |
<title>Silent Authentication Sample</title> | |
<style type="text/css"> | |
body { | |
font-family: "Segoe UI"; | |
} | |
</style> | |
</head> | |
<body> | |
<p> | |
This sample demonstrates silent authentication in a Microsoft Teams tab. | |
</p> | |
<p> | |
The tab will try to get an id token for the user silently, validate the token and show the profile information | |
decoded from the token. | |
The "Login" button will appear only if silent authentication failed. | |
</p> | |
<!-- Login button --> | |
<button id="btnLogin" onclick="login()" style="display: none">Login to Azure AD</button> | |
<!-- Result --> | |
<h2>id token data</h2> | |
<p> | |
<div id="divError" style="display: none"></div> | |
<div id="divProfile" style="display: none"> | |
<div><b>Name:</b> <span id="profileDisplayName" /></div> | |
<div><b>UPN:</b> <span id="profileUpn" /></div> | |
<div><b>Object id:</b> <span id="profileObjectId" /></div> | |
</div> | |
</p> | |
<h2>data from https://graph.microsoft.com/v1.0/me</h2> | |
<p> | |
<div id="divGraphError" style="display: none"></div> | |
<div id="divGraphProfile" style="display: none"> | |
<div><b>Name:</b> <span id="graphDisplayName" /></div> | |
<div><b>UPN:</b> <span id="graphUpn" /></div> | |
<div><b>Object id:</b> <span id="graphObjectId" /></div> | |
</div> | |
</p> | |
<h2>privileged data (Groups.Read.All) from https://graph.microsoft.com/v1.0/groups</h2> | |
<p> | |
<div id="divGraphGroupsError" style="display: none"></div> | |
<div id="divGraphGroupsProfile" style="display: none"> | |
<div><b>org group data:</b> <span id="graphGroupsResult" /></div> | |
</div> | |
</p> | |
<script src="https://code.jquery.com/jquery-3.1.1.js" | |
integrity="sha384-VC7EHu0lDzZyFfmjTPJq+DFyIn8TUGAJbEtpXquazFVr00Q/OOx//RjiZ9yU9+9m" | |
crossorigin="anonymous"></script> | |
<script src="https://statics.teams.microsoft.com/sdk/v1.5.2/js/MicrosoftTeams.min.js" | |
integrity="sha384-TJ2M0tW5fxu25/LwZie10M5O53iP1Q5FweiXk5rvfTHmvA7x2a6I9+KKi2pjAk6k" | |
crossorigin="anonymous"></script> | |
<!-- Check before upgrading your ADAL version, as this sample depends on an internal function to authenticate silently --> | |
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.17/js/adal.min.js"></script> | |
{{!-- <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.15/js/adal.min.js" | |
integrity="sha384-lIk8T3uMxKqXQVVfFbiw0K/Nq+kt1P3NtGt/pNexiDby2rKU6xnDY8p16gIwKqgI" | |
crossorigin="anonymous"></script> --}} | |
<script src="/assets/msal.js" type="text/javascript"></script> | |
<script type="text/javascript"> | |
microsoftTeams.initialize(); | |
// ADAL.js configuration | |
let config = { | |
clientId: "{{appId}}", | |
redirectUri: window.location.origin + "/tab-auth/silent-end", | |
cacheLocation: "localStorage", | |
navigateToLoginRequestUrl: false, | |
}; | |
let msalConfig = { | |
auth: { | |
clientId: "{{appId}}", | |
cacheLocation: "localStorage", | |
redirectUri: window.location.origin + "/tab-auth/silent-end" | |
}, | |
requestConfiguration: { | |
scopes: ["https://graph.microsoft.com/User.Read", "https://graph.microsoft.com/Group.Read.All"] | |
} | |
}; | |
let upn = undefined; | |
microsoftTeams.getContext(function (context) { | |
upn = context.upn; | |
if (upn) { | |
config.extraQueryParameters = "scope=openid+profile+https://graph.microsoft.com&login_hint=" + encodeURIComponent(upn); | |
} else { | |
config.extraQueryParameters = "scope=openid+profile+https://graph.microsoft.com"; | |
} | |
msalConfig.requestConfiguration.loginHint = upn; | |
loadData(upn); | |
}); | |
// Loads data for the given user | |
function loadData(upn) { | |
// ADAL | |
let authContext = new AuthenticationContext(config); | |
// See if there's a cached user and it matches the expected user | |
let user = authContext.getCachedUser(); | |
if (user) { | |
if (user.userName !== upn) { | |
// User doesn't match, clear the cache | |
authContext.clearCache(); | |
} | |
} | |
// get access token for resource (graph) | |
let accessToken = authContext.acquireToken("https://graph.microsoft.com", function (e, t, er) { | |
if (e || er) { | |
console.error("access e: " + e); | |
console.error("access er: " + er); | |
} | |
console.debug("access t: " + t); | |
queryGraph(t); | |
}); | |
// MSAL | |
let msalApp = new Msal.UserAgentApplication(msalConfig); | |
msalApp.handleRedirectCallback(() => { const notUsed = ""; }); | |
var tokenRequest = msalConfig.requestConfiguration; | |
msalApp.acquireTokenSilent(tokenRequest) | |
.then(response => { | |
console.log("got token with msal: " + response.accessToken); | |
}) | |
.catch(err => { | |
// could also check if err instance of InteractionRequiredAuthError if you can import the class. | |
console.error(err); | |
if (err.name === "InteractionRequiredAuthError") { | |
return msalApp.acquireTokenPopup(tokenRequest) | |
.then(response => { | |
// get access token from response | |
// response.accessToken | |
}) | |
.catch(err => { | |
// handle error | |
}); | |
} | |
}); | |
// if the user is already logged in you can acquire a token | |
if (msalApp.getAccount()) { | |
console.log("got account with msal"); | |
} else { | |
// user is not logged in, you will need to log them in to acquire a token | |
console.log("user not logged in via msal"); | |
} | |
} | |
function queryGraph(token) { | |
$.ajax({ | |
url: "https://graph.microsoft.com/v1.0/me", | |
beforeSend: function (request) { | |
request.setRequestHeader("Authorization", "Bearer " + token); | |
}, | |
success: function (data) { | |
$("#graphDisplayName").text(data.displayName); | |
$("#graphUpn").text(data.userPrincipalName); | |
$("#graphObjectId").text(data.id); | |
$("#divGraphProfile").css({ display: "" }); | |
$("#divGraphError").css({ display: "none" }); | |
}, | |
error: function (xhr, textStatus, errorThrown) { | |
console.log("textStatus: " + textStatus + ", errorThrown:" + errorThrown); | |
$("#divGraphError").text(errorThrown).css({ display: "" }); | |
$("#divGraphProfile").css({ display: "none" }); | |
}, | |
}); | |
//https://graph.microsoft.com/v1.0/groups | |
$.ajax({ | |
url: "https://graph.microsoft.com/v1.0/groups", | |
beforeSend: function (request) { | |
request.setRequestHeader("Authorization", "Bearer " + token); | |
}, | |
success: function (data) { | |
$("#graphGroupsResult").text(JSON.stringify(data)); | |
$("#divGraphGroupsProfile").css({ display: "" }); | |
$("#divGraphGroupsError").css({ display: "none" }); | |
}, | |
error: function (xhr, textStatus, errorThrown) { | |
console.log("textStatus: " + textStatus + ", errorThrown:" + errorThrown); | |
$("#divGraphGroupsError").text(errorThrown).css({ display: "" }); | |
$("#divGraphGroupsProfile").css({ display: "none" }); | |
}, | |
}); | |
} | |
// Login to Azure AD | |
function login() { | |
$("#divError").text("").css({ display: "none" }); | |
$("#divProfile").css({ display: "none" }); | |
microsoftTeams.authentication.authenticate({ | |
url: window.location.origin + "/tab-auth/silent-start", | |
width: 600, | |
height: 535, | |
successCallback: function (result) { | |
// AuthenticationContext is a singleton | |
let authContext = new AuthenticationContext(); | |
let idToken = authContext.getCachedToken(config.clientId); | |
if (idToken) { | |
showProfileInformation(idToken); | |
} else { | |
console.error("Error getting cached id token. This should never happen."); | |
// At this point we have to get the user involved, so show the login button | |
$("#btnLogin").css({ display: "" }); | |
}; | |
}, | |
failureCallback: function (reason) { | |
console.log("Login failed: " + reason); | |
if (reason === "CancelledByUser" || reason === "FailedToOpenWindow") { | |
console.log("Login was blocked by popup blocker or canceled by user."); | |
} | |
// At this point we have to get the user involved, so show the login button | |
$("#btnLogin").css({ display: "" }); | |
$("#divError").text(reason).css({ display: "" }); | |
$("#divProfile").css({ display: "none" }); | |
} | |
}); | |
} | |
// Get the user's profile information from the id token | |
function showProfileInformation(idToken) { | |
$.ajax({ | |
url: window.location.origin + "/api/validateToken", | |
beforeSend: function (request) { | |
request.setRequestHeader("Authorization", "Bearer " + idToken); | |
}, | |
success: function (token) { | |
$("#profileDisplayName").text(token.name); | |
$("#profileUpn").text(token.upn); | |
$("#profileObjectId").text(token.oid); | |
$("#divProfile").css({ display: "" }); | |
$("#divError").css({ display: "none" }); | |
}, | |
error: function (xhr, textStatus, errorThrown) { | |
console.log("textStatus: " + textStatus + ", errorThrown:" + errorThrown); | |
$("#divError").text(errorThrown).css({ display: "" }); | |
$("#divProfile").css({ display: "none" }); | |
}, | |
}); | |
} | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- | |
// Copyright (c) Microsoft Corporation | |
// All rights reserved. | |
// | |
// MIT License: | |
// Permission is hereby granted, free of charge, to any person obtaining | |
// a copy of this software and associated documentation files (the | |
// "Software"), to deal in the Software without restriction, including | |
// without limitation the rights to use, copy, modify, merge, publish, | |
// distribute, sublicense, and/or sell copies of the Software, and to | |
// permit persons to whom the Software is furnished to do so, subject to | |
// the following conditions: | |
// | |
// The above copyright notice and this permission notice shall be | |
// included in all copies or substantial portions of the Software. | |
// | |
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, | |
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | |
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE | |
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | |
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION | |
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
--> | |
<html> | |
<head> | |
<title>Silent Authentication Sample</title> | |
<style type="text/css"> | |
body { | |
font-family: "Segoe UI"; | |
} | |
</style> | |
</head> | |
<body> | |
<p> | |
This sample demonstrates silent authentication in a Microsoft Teams tab. | |
</p> | |
<p> | |
The tab will try to get an id token for the user silently, validate the token and show the profile information | |
decoded from the token. | |
The "Login" button will appear only if silent authentication failed. | |
</p> | |
<!-- Login button --> | |
<button id="btnLogin" onclick="login()" style="display: none">Login to Azure AD</button> | |
<!-- Result --> | |
<h2>id token data</h2> | |
<p> | |
<div id="divError" style="display: none"></div> | |
<div id="divProfile" style="display: none"> | |
<div><b>Name:</b> <span id="profileDisplayName" /></div> | |
<div><b>UPN:</b> <span id="profileUpn" /></div> | |
<div><b>Object id:</b> <span id="profileObjectId" /></div> | |
</div> | |
</p> | |
<h2>data from https://graph.microsoft.com/v1.0/me</h2> | |
<p> | |
<div id="divGraphError" style="display: none"></div> | |
<div id="divGraphProfile" style="display: none"> | |
<div><b>Name:</b> <span id="graphDisplayName" /></div> | |
<div><b>UPN:</b> <span id="graphUpn" /></div> | |
<div><b>Object id:</b> <span id="graphObjectId" /></div> | |
</div> | |
</p> | |
<h2>privileged data (Groups.Read.All) from https://graph.microsoft.com/v1.0/groups</h2> | |
<p> | |
<div id="divGraphGroupsError" style="display: none"></div> | |
<div id="divGraphGroupsProfile" style="display: none"> | |
<div><b>org group data:</b> <span id="graphGroupsResult" /></div> | |
</div> | |
</p> | |
<script src="https://code.jquery.com/jquery-3.1.1.js" | |
integrity="sha384-VC7EHu0lDzZyFfmjTPJq+DFyIn8TUGAJbEtpXquazFVr00Q/OOx//RjiZ9yU9+9m" | |
crossorigin="anonymous"></script> | |
<script src="https://statics.teams.microsoft.com/sdk/v1.5.2/js/MicrosoftTeams.min.js" | |
integrity="sha384-TJ2M0tW5fxu25/LwZie10M5O53iP1Q5FweiXk5rvfTHmvA7x2a6I9+KKi2pjAk6k" | |
crossorigin="anonymous"></script> | |
<!-- Check before upgrading your ADAL version, as this sample depends on an internal function to authenticate silently --> | |
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.15/js/adal.min.js" | |
integrity="sha384-lIk8T3uMxKqXQVVfFbiw0K/Nq+kt1P3NtGt/pNexiDby2rKU6xnDY8p16gIwKqgI" | |
crossorigin="anonymous"></script> | |
<script type="text/javascript"> | |
microsoftTeams.initialize(); | |
// ADAL.js configuration | |
let config = { | |
clientId: "{{appId}}", | |
redirectUri: window.location.origin + "/tab-auth/silent-end", // This should be in the list of redirect uris for the AAD app | |
cacheLocation: "localStorage", | |
navigateToLoginRequestUrl: false, | |
}; | |
let upn = undefined; | |
microsoftTeams.getContext(function (context) { | |
upn = context.upn; | |
loadData(upn); | |
}); | |
// Loads data for the given user | |
function loadData(upn) { | |
// Setup extra query parameters for ADAL | |
// - openid and profile scope adds profile information to the id_token | |
// - login_hint provides the expected user name | |
if (upn) { | |
config.extraQueryParameters = "scope=openid+profile+https://graph.microsoft.com&login_hint=" + encodeURIComponent(upn); | |
} else { | |
config.extraQueryParameters = "scope=openid+profile+https://graph.microsoft.com"; | |
} | |
let authContext = new AuthenticationContext(config); | |
// See if there's a cached user and it matches the expected user | |
let user = authContext.getCachedUser(); | |
if (user) { | |
if (user.userName !== upn) { | |
// User doesn't match, clear the cache | |
authContext.clearCache(); | |
} | |
} | |
// Get the id token (which is the access token for resource = clientId) | |
let accessToken = authContext.acquireToken("https://graph.microsoft.com", function (e, t, er) { | |
console.error("access e: " + e); | |
console.debug("access t: " + t); | |
console.error("access er: " + er); | |
queryGraph(t); | |
}); | |
// Get the id token (which is the access token for resource = clientId) | |
let token = authContext.getCachedToken(config.clientId); | |
if (token) { | |
console.debug("id token for " + config.clientId + ": " + token); | |
showProfileInformation(token); | |
} else { | |
// No token, or token is expired | |
authContext._renewIdToken(function (err, idToken) { | |
if (err) { | |
console.log("Renewal failed: " + err); | |
// Failed to get the token silently; show the login button | |
$("#btnLogin").css({ display: "" }); | |
// You could attempt to launch the login popup here, but in browsers this could be blocked by | |
// a popup blocker, in which case the login attempt will fail with the reason FailedToOpenWindow. | |
} else { | |
showProfileInformation(idToken); | |
} | |
}); | |
} | |
} | |
function queryGraph(token) { | |
$.ajax({ | |
url: "https://graph.microsoft.com/v1.0/me", | |
beforeSend: function (request) { | |
request.setRequestHeader("Authorization", "Bearer " + token); | |
}, | |
success: function (data) { | |
$("#graphDisplayName").text(data.displayName); | |
$("#graphUpn").text(data.userPrincipalName); | |
$("#graphObjectId").text(data.id); | |
$("#divGraphProfile").css({ display: "" }); | |
$("#divGraphError").css({ display: "none" }); | |
}, | |
error: function (xhr, textStatus, errorThrown) { | |
console.log("textStatus: " + textStatus + ", errorThrown:" + errorThrown); | |
$("#divGraphError").text(errorThrown).css({ display: "" }); | |
$("#divGraphProfile").css({ display: "none" }); | |
}, | |
}); | |
//https://graph.microsoft.com/v1.0/groups | |
$.ajax({ | |
url: "https://graph.microsoft.com/v1.0/groups", | |
beforeSend: function (request) { | |
request.setRequestHeader("Authorization", "Bearer " + token); | |
}, | |
success: function (data) { | |
$("#graphGroupsResult").text(JSON.stringify(data)); | |
$("#divGraphGroupsProfile").css({ display: "" }); | |
$("#divGraphGroupsError").css({ display: "none" }); | |
}, | |
error: function (xhr, textStatus, errorThrown) { | |
console.log("textStatus: " + textStatus + ", errorThrown:" + errorThrown); | |
$("#divGraphGroupsError").text(errorThrown).css({ display: "" }); | |
$("#divGraphGroupsProfile").css({ display: "none" }); | |
}, | |
}); | |
} | |
// Login to Azure AD | |
function login() { | |
$("#divError").text("").css({ display: "none" }); | |
$("#divProfile").css({ display: "none" }); | |
microsoftTeams.authentication.authenticate({ | |
url: window.location.origin + "/tab-auth/silent-start", | |
width: 600, | |
height: 535, | |
successCallback: function (result) { | |
// AuthenticationContext is a singleton | |
let authContext = new AuthenticationContext(); | |
let idToken = authContext.getCachedToken(config.clientId); | |
if (idToken) { | |
showProfileInformation(idToken); | |
} else { | |
console.error("Error getting cached id token. This should never happen."); | |
// At this point we have to get the user involved, so show the login button | |
$("#btnLogin").css({ display: "" }); | |
}; | |
}, | |
failureCallback: function (reason) { | |
console.log("Login failed: " + reason); | |
if (reason === "CancelledByUser" || reason === "FailedToOpenWindow") { | |
console.log("Login was blocked by popup blocker or canceled by user."); | |
} | |
// At this point we have to get the user involved, so show the login button | |
$("#btnLogin").css({ display: "" }); | |
$("#divError").text(reason).css({ display: "" }); | |
$("#divProfile").css({ display: "none" }); | |
} | |
}); | |
} | |
// Get the user's profile information from the id token | |
function showProfileInformation(idToken) { | |
$.ajax({ | |
url: window.location.origin + "/api/validateToken", | |
beforeSend: function (request) { | |
request.setRequestHeader("Authorization", "Bearer " + idToken); | |
}, | |
success: function (token) { | |
$("#profileDisplayName").text(token.name); | |
$("#profileUpn").text(token.upn); | |
$("#profileObjectId").text(token.oid); | |
$("#divProfile").css({ display: "" }); | |
$("#divError").css({ display: "none" }); | |
}, | |
error: function (xhr, textStatus, errorThrown) { | |
console.log("textStatus: " + textStatus + ", errorThrown:" + errorThrown); | |
$("#divError").text(errorThrown).css({ display: "" }); | |
$("#divProfile").css({ display: "none" }); | |
}, | |
}); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment