This repository has been archived by the owner on Nov 16, 2023. It is now read-only.
/
silent.hbs
177 lines (159 loc) · 8.47 KB
/
silent.hbs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
<!--
// 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>
</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 -->
<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>
<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.0/js/MicrosoftTeams.min.js" integrity="sha384-SNENyRfvDvybst1u0LawETYF6L5yMx5Ya1dIqWoG4UDTZ/5UAMB15h37ktdBbyFh" 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();
let upn = undefined;
microsoftTeams.getContext(function (context) {
upn = context.upn;
loadData(upn);
});
// Loads data for the given user
function loadData(upn) {
// 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,
};
// 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&login_hint=" + encodeURIComponent(upn);
} else {
config.extraQueryParameters = "scope=openid+profile";
}
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 token = authContext.getCachedToken(config.clientId);
if (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);
}
});
}
}
// 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>