public HttpClient Create(HttpAuthentication auth) { HttpMessageHandler handler; handler = _httpClientHandlerFactory.Create(); var settings = _settingsManager.ReadSettings(); var tokenCache = _settingsManager.GetTokenCache(); var tokenProvider = new TokenProvider(settings, tokenCache, _console); if (auth != null) { handler = new AuthenticationTokenMessageHandler(() => tokenProvider.AcquireTokenAsync(auth)) { InnerHandler = handler }; } handler = new LambdaDelegatingHandler(handler, SharedKeyAuthentication); handler = new LambdaDelegatingHandler(handler, async (request, cancellationToken, next) => { var sw = new Stopwatch(); try { // _logger.LogInformation("{Method} {Url}", request.Method, request.RequestUri); _console.WriteLine($"{request.Method.ToString().Color(ConsoleColor.DarkGreen)} {request.RequestUri}"); sw.Start(); var response = await next(request, cancellationToken); sw.Stop(); _console.WriteLine($"{response.StatusCode.ToString().Color((int)response.StatusCode >= 400 ? ConsoleColor.Red : ConsoleColor.Green)} {request.RequestUri} {sw.ElapsedMilliseconds}ms"); return response; } catch { Console.WriteLine($"{"FAIL".Color(ConsoleColor.DarkRed)} {request.RequestUri} {sw.ElapsedMilliseconds}ms"); throw; } }); return new HttpClient(handler); }
public async Task <AuthenticationHeaderValue> AcquireTokenAsync(HttpAuthentication auth) { var tenant = auth.tenant; var resourceId = auth.resourceId; var clientId = auth.clientId; // https://login.microsoftonline.com // https://login.windows.net var authority = $"https://login.windows.net/{tenant ?? "common"}"; AccountEntry account = null; if (account == null) { account = _settings.accounts.Where(entry => string.Equals(entry.authority, authority, StringComparison.Ordinal) && string.Equals(entry.resource, resourceId, StringComparison.Ordinal)).LastOrDefault(); } if (account == null) { account = _settings.accounts.Where(entry => string.IsNullOrEmpty(entry.authority) && string.Equals(entry.resource, resourceId, StringComparison.Ordinal)).LastOrDefault(); } if (account == null) { account = _settings.accounts.Where(entry => string.Equals(entry.authority, authority, StringComparison.Ordinal) && string.IsNullOrEmpty(entry.resource)).LastOrDefault(); } if (account == null) { account = _settings.accounts.Where(entry => string.IsNullOrEmpty(entry.authority) && string.IsNullOrEmpty(entry.resource)).LastOrDefault(); } var ctx = new AuthenticationContext(authority, _tokenCache); AuthenticationResult result = null; if (account != null) { if (!string.IsNullOrEmpty(account.token)) { return(new AuthenticationHeaderValue("Bearer", account.token)); } else if (!string.IsNullOrEmpty(account.password)) { var basic = $"{account.username}:{account.password}"; return(new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(basic)))); } else if (!string.IsNullOrEmpty(account.appid)) { result = await ctx.AcquireTokenAsync(resourceId, new ClientCredential(account.appid, account.secret)); } else { throw new InvalidOperationException("Account entry requires either token or appid and secret values."); } } else { if (auth.interactive == false) { throw new InvalidOperationException("Matching account credentials have not been stored, and interactive authentication is disallowed."); } try { result = await ctx.AcquireTokenSilentAsync(resourceId, clientId); } catch { DeviceCodeResult codeResult = await ctx.AcquireDeviceCodeAsync(resourceId, clientId); _console.Error.WriteLine(codeResult.Message.Color(ConsoleColor.DarkYellow)); result = await ctx.AcquireTokenByDeviceCodeAsync(codeResult); } } return(new AuthenticationHeaderValue(result.AccessTokenType, result.AccessToken)); }