Reputation: 811
I have a WCF service that needs to ultimately get a token to talk to a web api service hosted in azure. Our on premise active directory is synced with our azure account.
Initially I had a play in a win forms app and got a token successfully using the following:
AuthenticationResult authResult = authContext.AcquireToken(apiResourceId, clientId, redirectUri);
This though popped up a login dialog so not much use for a windows service. I then investigated the use of AcquireTokenSilent(). This however kept throwing an exception telling me to call AcquireToken so back to square 1.
My next port of call was to look at AcquireTokenByAuthorizationCode(). My problem with this though is how to acquire an authorisation code which is the first parameter.
I've tried:
var url = authContext.GetAuthorizationRequestURL(apiResourceId, clientId, redirectUri, UserIdentifier.AnyUser, string.Empty);
HttpClient hc = new HttpClient();
HttpResponseMessage hrm = hc.GetAsync(url).Result;
This though just returns an html page showing i think a microsoft login page. It certainly doesn't contain any code.
Any ideas on what I am doing wrong?
Upvotes: 0
Views: 2299
Reputation: 7394
The AcquireTokenSilent works only if you already have tokens in the cache, which is not the case in your scenario. The AcquireTokenByAuthorizationCode is meant to be sued on the server side. The main ways in which you can get a token without popping out a dialog on a client are shown in https://github.com/Azure-Samples/active-directory-dotnet-native-headless, but there are important limitations. If they work in your scenario fine, otherwise you might consider creating a persistent cache, priming it by doing one interactive authentication, and then keep using the same cache from your service via AcquireTokenSilent. The cached refresh token will last 90 days as long as you use it at least once every 14 days.
Upvotes: 2