Skip to content

Instantly share code, notes, and snippets.

@coreyroth
Created August 14, 2015 17:45
Show Gist options
  • Save coreyroth/4aef2435418773ae21b4 to your computer and use it in GitHub Desktop.
Save coreyroth/4aef2435418773ae21b4 to your computer and use it in GitHub Desktop.
public async Task<string> GetAccessTokenForResource(string resource)
{
string token = null;
//first try to get the token silently
WebAccountProvider aadAccountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.windows.net");
WebTokenRequest webTokenRequest = new WebTokenRequest(aadAccountProvider, String.Empty, App.Current.Resources["ida:ClientID"].ToString(), WebTokenRequestPromptType.Default);
webTokenRequest.Properties.Add("authority", "https://login.windows.net");
webTokenRequest.Properties.Add("resource", resource);
WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest);
if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
{
WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
token = webTokenResponse.Token;
}
else if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.UserInteractionRequired)
{
//get token through prompt
webTokenRequest = new WebTokenRequest(aadAccountProvider, String.Empty, App.Current.Resources["ida:ClientID"].ToString(), WebTokenRequestPromptType.ForceAuthentication);
webTokenRequest.Properties.Add("authority", "https://login.windows.net");
webTokenRequest.Properties.Add("resource", resource);
webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
{
WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0];
token = webTokenResponse.Token;
}
}
return token;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment