public async Task <IMsalToken> AcquireTokenWithUI(CancellationToken cancellationToken, ILogger logging) { var deviceFlowTimeout = EnvUtil.GetDeviceFlowTimeoutFromEnvironmentInSeconds(logging); CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(deviceFlowTimeout)); var linkedCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token).Token; var publicClient = await GetPCAAsync(useLocalHost : true).ConfigureAwait(false); try { var msalBuilder = publicClient.AcquireTokenInteractive(new string[] { resource }); msalBuilder.WithPrompt(Prompt.SelectAccount); msalBuilder.WithUseEmbeddedWebView(false); var result = await msalBuilder.ExecuteAsync(linkedCancellationToken); return(new MsalToken(result)); } catch (MsalServiceException e) { if (e.ErrorCode.Contains(MsalError.AuthenticationCanceledError)) { return(null); } throw; } finally { var helper = await GetMsalCacheHelperAsync(); helper?.UnregisterCache(publicClient.UserTokenCache); } }
public async Task <IMsalToken> AcquireTokenWithDeviceFlowAsync(Func <DeviceCodeResult, Task> deviceCodeHandler, CancellationToken cancellationToken, ILogger logger) { var deviceFlowTimeout = EnvUtil.GetDeviceFlowTimeoutFromEnvironmentInSeconds(logger); CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(deviceFlowTimeout)); var linkedCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token).Token; linkedCancellationToken.ThrowIfCancellationRequested(); var publicClient = await GetPCAAsync().ConfigureAwait(false); try { var msalBuilder = publicClient.AcquireTokenWithDeviceCode(new string[] { resource }, deviceCodeHandler); var result = await msalBuilder.ExecuteAsync(linkedCancellationToken); return(new MsalToken(result)); } finally { var helper = await GetMsalCacheHelperAsync(); helper?.UnregisterCache(publicClient.UserTokenCache); } }
public async Task <IAdalToken> AcquireTokenWithDeviceFlowAsync(Func <DeviceCodeResult, Task> deviceCodeHandler, CancellationToken cancellationToken, ILogger logger) { var authenticationContext = new AuthenticationContext(authority, tokenCache); var deviceCode = await authenticationContext.AcquireDeviceCodeAsync(resource, clientId); cancellationToken.ThrowIfCancellationRequested(); if (deviceCodeHandler != null) { await deviceCodeHandler(deviceCode); cancellationToken.ThrowIfCancellationRequested(); } AuthenticationResult result = null; var deviceFlowTimeout = EnvUtil.GetDeviceFlowTimeoutFromEnvironmentInSeconds(logger); var task = authenticationContext.AcquireTokenByDeviceCodeAsync(deviceCode); if (await Task.WhenAny(task, Task.Delay(deviceFlowTimeout * 1000, cancellationToken)) == task) { result = await task; } else { logger.Error(string.Format(Resources.DeviceFlowTimedOut, deviceFlowTimeout)); } return(new AdalToken(result)); }