Aussie
Aussie

Reputation: 83

Null Exception if authContext.AcquireTokenAsync is called in UWP

I am writing a UWP application with ADAL authentication. The UWP app won't have much user interaction. Therefore I like to use ClientCredtial() and then the app will work without user login.

If I use ClientCredential() in authContext.AcquireTokenAsync(), I've got a very weird error message "System.ArgumentNullException: 'Value cannot be null.'".

It works perfect in a console program (https://github.com/Azure-Samples/active-directory-dotnet-daemon) but it works only once but it will fail after the first success in the UWP app. I mean it doesn't work from the 2nd attempt. clientCredential = new ClientCredential(clientId, appKey); result = await authContext.AcquireTokenAsync(ResourceId, clientCredential);

However the method (authContext.AcquireTokenAsync) works fine with other parameters such as client id, etc as below. result = await authContext.AcquireTokenSilentAsync(ResourceId, clientId);

Does UWP have got restriction on authContext.AcquireTokenSilentAsync() with ClientCredential(clientid, key)?

Upvotes: 1

Views: 677

Answers (1)

Aussie
Aussie

Reputation: 83

I think ADAL for UWP has a bug in it.

However there is an workaround to avoid the error 'Value cannot be null.'". First I checked if a token cache is available. If available, the existing token will be used.

At least, it works for me.

TokenCacheItem tItem = authContext.TokenCache.ReadItems().FirstOrDefault();
if (tItem != null) //use the exsting token.
    token = tItem.AccessToken;
else // get a new token if not available.
{
    result = await authContext.AcquireTokenAsync   (resourceid, clientCredential);
    token = result.AccessToken;
}

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

In console application, you don't need the above solution. It works without checking caches.

Upvotes: 1

Related Questions