-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
InteractiveBrowserCredential.cs
375 lines (344 loc) · 21 KB
/
InteractiveBrowserCredential.cs
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Microsoft.Identity.Client;
namespace Azure.Identity
{
/// <summary>
/// A <see cref="TokenCredential"/> implementation which launches the system default browser to interactively authenticate a user, and obtain an access token.
/// The browser will only be launched to authenticate the user once, then will silently acquire access tokens through the users refresh token as long as it's valid.
/// </summary>
public class InteractiveBrowserCredential : TokenCredential
#if PREVIEW_FEATURE_FLAG
, ISupportsProofOfPossession
#endif
{
internal string TenantId { get; }
internal string[] AdditionallyAllowedTenantIds { get; }
internal string ClientId { get; }
internal string LoginHint { get; }
internal BrowserCustomizationOptions BrowserCustomization { get; }
internal MsalPublicClient Client { get; }
internal CredentialPipeline Pipeline { get; }
internal bool DisableAutomaticAuthentication { get; }
internal AuthenticationRecord Record { get; set; }
internal string DefaultScope { get; }
internal TenantIdResolverBase TenantIdResolver { get; }
internal bool UseOperatingSystemAccount { get; }
private const string AuthenticationRequiredMessage = "Interactive authentication is needed to acquire token. Call Authenticate to interactively authenticate.";
private const string NoDefaultScopeMessage = "Authenticating in this environment requires specifying a TokenRequestContext.";
/// <summary>
/// Creates a new <see cref="InteractiveBrowserCredential"/> with the specified options, which will authenticate users.
/// </summary>
public InteractiveBrowserCredential()
: this(null, Constants.DeveloperSignOnClientId, null, null)
{ }
/// <summary>
/// Creates a new <see cref="InteractiveBrowserCredential"/> with the specified options, which will authenticate users with the specified application.
/// </summary>
/// <param name="options">The client options for the newly created <see cref="InteractiveBrowserCredential"/>.</param>
public InteractiveBrowserCredential(InteractiveBrowserCredentialOptions options)
: this(options?.TenantId, options?.ClientId ?? Constants.DeveloperSignOnClientId, options, null)
{
DisableAutomaticAuthentication = options?.DisableAutomaticAuthentication ?? false;
Record = options?.AuthenticationRecord;
}
/// <summary>
/// Creates a new <see cref="InteractiveBrowserCredential"/> with the specified options, which will authenticate users with the specified application.
/// </summary>
/// <param name="clientId">The client id of the application to which the users will authenticate</param>
[EditorBrowsable(EditorBrowsableState.Never)]
public InteractiveBrowserCredential(string clientId)
: this(null, clientId, null, null)
{ }
/// <summary>
/// Creates a new <see cref="InteractiveBrowserCredential"/> with the specified options, which will authenticate users with the specified application.
/// </summary>
/// <param name="tenantId">The tenant id of the application and the users to authenticate. Can be null in the case of multi-tenant applications.</param>
/// <param name="clientId">The client id of the application to which the users will authenticate</param>
/// TODO: need to link to info on how the application has to be created to authenticate users, for multiple applications
/// <param name="options">The client options for the newly created <see cref="InteractiveBrowserCredential"/>.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
public InteractiveBrowserCredential(string tenantId, string clientId, TokenCredentialOptions options = default)
: this(Validations.ValidateTenantId(tenantId, nameof(tenantId), allowNull: true), clientId, options, null, null)
{
Argument.AssertNotNull(clientId, nameof(clientId));
}
internal InteractiveBrowserCredential(string tenantId, string clientId, TokenCredentialOptions options, CredentialPipeline pipeline)
: this(tenantId, clientId, options, pipeline, null)
{
Argument.AssertNotNull(clientId, nameof(clientId));
}
internal InteractiveBrowserCredential(string tenantId, string clientId, TokenCredentialOptions options, CredentialPipeline pipeline, MsalPublicClient client)
{
ClientId = clientId;
TenantId = tenantId;
Pipeline = pipeline ?? CredentialPipeline.GetInstance(options);
LoginHint = (options as InteractiveBrowserCredentialOptions)?.LoginHint;
var redirectUrl = (options as InteractiveBrowserCredentialOptions)?.RedirectUri?.AbsoluteUri ?? Constants.DefaultRedirectUrl;
DefaultScope = AzureAuthorityHosts.GetDefaultScope(options?.AuthorityHost ?? AzureAuthorityHosts.GetDefault());
Client = client ?? new MsalPublicClient(Pipeline, tenantId, clientId, redirectUrl, options);
TenantIdResolver = options?.TenantIdResolver ?? TenantIdResolverBase.Default;
AdditionallyAllowedTenantIds = TenantIdResolver.ResolveAddionallyAllowedTenantIds((options as ISupportsAdditionallyAllowedTenants)?.AdditionallyAllowedTenants);
Record = (options as InteractiveBrowserCredentialOptions)?.AuthenticationRecord;
BrowserCustomization = (options as InteractiveBrowserCredentialOptions)?.BrowserCustomization;
UseOperatingSystemAccount = (options as IMsalPublicClientInitializerOptions)?.UseDefaultBrokerAccount ?? false;
}
/// <summary>
/// Interactively authenticates a user via the default browser.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The result of the authentication request, containing the acquired <see cref="AccessToken"/>, and the <see cref="AuthenticationRecord"/> which can be used to silently authenticate the account.</returns>
public virtual AuthenticationRecord Authenticate(CancellationToken cancellationToken = default)
{
// throw if no default scope exists
if (DefaultScope == null)
{
throw new CredentialUnavailableException(NoDefaultScopeMessage);
}
return Authenticate(new TokenRequestContext(new[] { DefaultScope }), cancellationToken);
}
/// <summary>
/// Interactively authenticates a user via the default browser. The resulting <see cref="AuthenticationRecord"/> will automatically be used in subsequent calls to <see cref="GetTokenAsync(TokenRequestContext, CancellationToken)"/>.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>The result of the authentication request, containing the acquired <see cref="AccessToken"/>, and the <see cref="AuthenticationRecord"/> which can be used to silently authenticate the account.</returns>
public virtual async Task<AuthenticationRecord> AuthenticateAsync(CancellationToken cancellationToken = default)
{
// throw if no default scope exists
if (DefaultScope == null)
{
throw new CredentialUnavailableException(NoDefaultScopeMessage);
}
return await AuthenticateAsync(new TokenRequestContext(new string[] { DefaultScope }), cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Interactively authenticates a user via the default browser. The resulting <see cref="AuthenticationRecord"/> will automatically be used in subsequent calls to <see cref="GetToken(TokenRequestContext, CancellationToken)"/>.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <param name="requestContext">The details of the authentication request.</param>
/// <returns>The <see cref="AuthenticationRecord"/> of the authenticated account.</returns>
public virtual AuthenticationRecord Authenticate(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
{
#if PREVIEW_FEATURE_FLAG
return AuthenticateImplAsync(false, PopTokenRequestContext.FromTokenRequestContext(requestContext), cancellationToken).EnsureCompleted();
#else
return AuthenticateImplAsync(false, requestContext, cancellationToken).EnsureCompleted();
#endif
}
/// <summary>
/// Interactively authenticates a user via the default browser.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <param name="requestContext">The details of the authentication request.</param>
/// <returns>The <see cref="AuthenticationRecord"/> of the authenticated account.</returns>
public virtual async Task<AuthenticationRecord> AuthenticateAsync(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
{
#if PREVIEW_FEATURE_FLAG
return await AuthenticateImplAsync(true, PopTokenRequestContext.FromTokenRequestContext(requestContext), cancellationToken).ConfigureAwait(false);
#else
return await AuthenticateImplAsync(true, requestContext, cancellationToken).ConfigureAwait(false);
#endif
}
/// <summary>
/// Obtains an <see cref="AccessToken"/> token for a user account silently if the user has already authenticated, otherwise the
/// default browser is launched to authenticate the user. Acquired tokens are cached by the credential instance. Token lifetime and
/// refreshing is handled automatically. Where possible, reuse credential instances to optimize cache effectiveness.
/// </summary>
/// <param name="requestContext">The details of the authentication request.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls.</returns>
public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
{
#if PREVIEW_FEATURE_FLAG
return GetTokenImplAsync(false, PopTokenRequestContext.FromTokenRequestContext(requestContext), cancellationToken).EnsureCompleted();
#else
return GetTokenImplAsync(false, requestContext, cancellationToken).EnsureCompleted();
#endif
}
/// <summary>
/// Obtains an <see cref="AccessToken"/> token for a user account silently if the user has already authenticated, otherwise the
/// default browser is launched to authenticate the user. Acquired tokens are cached by the credential instance. Token lifetime and
/// refreshing is handled automatically. Where possible, reuse credential instances to optimize cache effectiveness.
/// </summary>
/// <param name="requestContext">The details of the authentication request.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls.</returns>
public override async ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
{
#if PREVIEW_FEATURE_FLAG
return await GetTokenImplAsync(true, PopTokenRequestContext.FromTokenRequestContext(requestContext), cancellationToken).ConfigureAwait(false);
#else
return await GetTokenImplAsync(true, requestContext, cancellationToken).ConfigureAwait(false);
#endif
}
#if PREVIEW_FEATURE_FLAG
/// <summary>
/// Obtains an <see cref="AccessToken"/> token for a user account silently if the user has already authenticated, otherwise the
/// default browser is launched to authenticate the user. Acquired tokens are cached by the credential instance. Token lifetime and
/// refreshing is handled automatically. Where possible, reuse credential instances to optimize cache effectiveness.
/// </summary>
/// <param name="requestContext">The details of the authentication request.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls.</returns>
public AccessToken GetToken(PopTokenRequestContext requestContext, CancellationToken cancellationToken = default)
{
return GetTokenImplAsync(false, requestContext, cancellationToken).EnsureCompleted();
}
/// <summary>
/// Obtains an <see cref="AccessToken"/> token for a user account silently if the user has already authenticated, otherwise the
/// default browser is launched to authenticate the user. Acquired tokens are cached by the credential instance. Token lifetime and
/// refreshing is handled automatically. Where possible, reuse credential instances to optimize cache effectiveness.
/// </summary>
/// <param name="requestContext">The details of the authentication request.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls.</returns>
public async ValueTask<AccessToken> GetTokenAsync(PopTokenRequestContext requestContext, CancellationToken cancellationToken = default)
{
return await GetTokenImplAsync(true, requestContext, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Interactively authenticates a user via the default browser. The resulting <see cref="AuthenticationRecord"/> will automatically be used in subsequent calls to <see cref="GetToken(TokenRequestContext, CancellationToken)"/>.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <param name="requestContext">The details of the authentication request.</param>
/// <returns>The <see cref="AuthenticationRecord"/> of the authenticated account.</returns>
public virtual AuthenticationRecord Authenticate(PopTokenRequestContext requestContext, CancellationToken cancellationToken = default)
{
return AuthenticateImplAsync(false, requestContext, cancellationToken).EnsureCompleted();
}
/// <summary>
/// Interactively authenticates a user via the default browser.
/// </summary>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
/// <param name="requestContext">The details of the authentication request.</param>
/// <returns>The <see cref="AuthenticationRecord"/> of the authenticated account.</returns>
public virtual async Task<AuthenticationRecord> AuthenticateAsync(PopTokenRequestContext requestContext, CancellationToken cancellationToken = default)
{
return await AuthenticateImplAsync(true, requestContext, cancellationToken).ConfigureAwait(false);
}
#endif
#if PREVIEW_FEATURE_FLAG
private async Task<AuthenticationRecord> AuthenticateImplAsync(bool async, PopTokenRequestContext requestContext, CancellationToken cancellationToken)
#else
private async Task<AuthenticationRecord> AuthenticateImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
#endif
{
using CredentialDiagnosticScope scope = Pipeline.StartGetTokenScope($"{nameof(InteractiveBrowserCredential)}.{nameof(Authenticate)}", requestContext);
try
{
scope.Succeeded(await GetTokenViaBrowserLoginAsync(requestContext, async, cancellationToken).ConfigureAwait(false));
return Record;
}
catch (Exception e)
{
throw scope.FailWrapAndThrow(e);
}
}
#if PREVIEW_FEATURE_FLAG
private async ValueTask<AccessToken> GetTokenImplAsync(bool async, PopTokenRequestContext requestContext, CancellationToken cancellationToken)
#else
private async ValueTask<AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken)
#endif
{
using CredentialDiagnosticScope scope = Pipeline.StartGetTokenScope($"{nameof(InteractiveBrowserCredential)}.{nameof(GetToken)}", requestContext);
try
{
Exception inner = null;
var tenantId = TenantIdResolver.Resolve(TenantId ?? Record?.TenantId, requestContext, AdditionallyAllowedTenantIds);
if (Record is not null || UseOperatingSystemAccount)
{
try
{
AuthenticationResult result;
if (Record is null)
{
result = await Client
.AcquireTokenSilentAsync(
requestContext.Scopes,
requestContext.Claims,
PublicClientApplication.OperatingSystemAccount,
tenantId,
requestContext.IsCaeEnabled,
#if PREVIEW_FEATURE_FLAG
requestContext,
#endif
async,
cancellationToken)
.ConfigureAwait(false);
}
else
{
result = await Client
.AcquireTokenSilentAsync(
requestContext.Scopes,
requestContext.Claims,
Record,
tenantId,
requestContext.IsCaeEnabled,
#if PREVIEW_FEATURE_FLAG
requestContext,
#endif
async,
cancellationToken)
.ConfigureAwait(false);
}
return scope.Succeeded(result.ToAccessToken());
}
catch (MsalUiRequiredException e)
{
inner = e;
}
}
if (DisableAutomaticAuthentication)
{
#if PREVIEW_FEATURE_FLAG
throw new AuthenticationRequiredException(AuthenticationRequiredMessage, requestContext.ToTokenRequestContext(), inner);
#else
throw new AuthenticationRequiredException(AuthenticationRequiredMessage, requestContext, inner);
#endif
}
return scope.Succeeded(await GetTokenViaBrowserLoginAsync(requestContext, async, cancellationToken).ConfigureAwait(false));
}
catch (Exception e)
{
throw scope.FailWrapAndThrow(e);
}
}
#if PREVIEW_FEATURE_FLAG
private async Task<AccessToken> GetTokenViaBrowserLoginAsync(PopTokenRequestContext context, bool async, CancellationToken cancellationToken)
#else
private async Task<AccessToken> GetTokenViaBrowserLoginAsync(TokenRequestContext context, bool async, CancellationToken cancellationToken)
#endif
{
Prompt prompt = LoginHint switch
{
null => Prompt.SelectAccount,
_ => Prompt.NoPrompt
};
var tenantId = TenantIdResolver.Resolve(TenantId ?? Record?.TenantId, context, AdditionallyAllowedTenantIds);
AuthenticationResult result = await Client
.AcquireTokenInteractiveAsync(
context.Scopes,
context.Claims,
prompt,
LoginHint,
tenantId,
context.IsCaeEnabled,
BrowserCustomization,
#if PREVIEW_FEATURE_FLAG
context,
#endif
async,
cancellationToken)
.ConfigureAwait(false);
Record = new AuthenticationRecord(result, ClientId);
return new AccessToken(result.AccessToken, result.ExpiresOn);
}
}
}