Subsequent calls to AcquireToken()

Using the Active Directory Authentication Library (ADAL) and getting that annoying flash from the authentication dialog on subsequent calls? Maybe you’re creating a new AuthenticationContext every time? In that case the call to AcquireToke() by the context cannot keep and lookup the cached token and refreshtokens. You should try to keep a cached or static version of the AuthenticationContext alive between calls. Something like this of you’re calling a web api or similar:

private static readonly AuthenticationContext AuthenticationContext = new AuthenticationContext("https://login.windows.net/domain.com");

private static AuthenticationResult GetAuthenticationToken()
{
var acquireToken = AuthenticationContext.AcquireToken("https://domain.com/WebApp-something.azurewebsites.net", //resource id of the web api
"acca2f90-5f76-45b5-8ec3------", //the client id
new Uri("https://domain.com/YourClientRedirectUrl")); //client redirect url

return acquireToken;
}

public static async Task<string> GetRequestAsync(string requestUri)
{
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
var authorizationHeader = GetAuthenticationToken().CreateAuthorizationHeader();
request.Headers.TryAddWithoutValidation("Authorization", authorizationHeader);
var response = await client.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
Debug.WriteLine(responseString);
return responseString;
}

No Comments