Created
October 8, 2017 19:52
-
-
Save fabiomaulo/1a3d6a29ce27a3c566c405225ddbf714 to your computer and use it in GitHub Desktop.
HttpClient handler with Auth using AAD
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
/// <summary> | |
/// AuthHandler for AAD | |
/// </summary> | |
public class ActiveDirectoryAuthHandler : DelegatingHandler | |
{ | |
private const int maxAuthRetry = 3; | |
private readonly AuthenticationContext authContext; | |
private readonly ClientCredential clientCredential; | |
private readonly string appIdUri; | |
public ActiveDirectoryAuthHandler(AuthenticationContext authContext | |
, ClientCredential clientCredential | |
, string appIdUri | |
, HttpMessageHandler innerHandler) : base(innerHandler) | |
{ | |
this.authContext = authContext ?? throw new ArgumentNullException(nameof(authContext)); | |
this.clientCredential = clientCredential ?? throw new ArgumentNullException(nameof(clientCredential)); | |
this.appIdUri = appIdUri ?? throw new ArgumentNullException(nameof(appIdUri)); | |
} | |
public ActiveDirectoryAuthHandler(AuthenticationContext authContext | |
, ClientCredential clientCredential | |
, string appIdUri) : base(new HttpClientHandler()) | |
{ | |
this.authContext = authContext ?? throw new ArgumentNullException(nameof(authContext)); | |
this.clientCredential = clientCredential ?? throw new ArgumentNullException(nameof(clientCredential)); | |
this.appIdUri = appIdUri ?? throw new ArgumentNullException(nameof(appIdUri)); | |
} | |
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | |
{ | |
var authResult = await GetAuth(); | |
if (authResult != null) | |
{ | |
request.Headers.Authorization = new AuthenticationHeaderValue(authResult.AccessTokenType, authResult.AccessToken); | |
} | |
return await base.SendAsync(request, cancellationToken); | |
} | |
private async Task<AuthenticationResult> GetAuth() | |
{ | |
int retryCount = 0; | |
bool mustRetry; | |
do | |
{ | |
mustRetry = false; | |
try | |
{ | |
// ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired. | |
return await authContext.AcquireTokenAsync(appIdUri, clientCredential); | |
} | |
catch (AdalException ex) when (ex.ErrorCode == "temporarily_unavailable") | |
{ | |
mustRetry = true; | |
retryCount++; | |
await Task.Delay(3000); | |
} | |
} while ((mustRetry == true) && (retryCount < maxAuthRetry)); | |
return null; | |
} | |
} |
Author
fabiomaulo
commented
Oct 8, 2017
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment