-
Notifications
You must be signed in to change notification settings - Fork 214
Using the acquired token to call a protected Web API
Getting a token is not a goal per se. It's a necessary step to call a protected API. The token needs then to be used to access a Web API. The way to do it, is by setting the Authorization header to be "Bearer", followed by a space, followed by the access token.
Note that the code below shows how to call directly the web API with an HttpClient. You can also use libraries which will only require the access token (DocumentDb for instance) and will take care of the headers details. In practice the code might change depending on the libraries you want to call
// Using the token
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", result.CreateAuthorizationHeader());
HttpResponseMessage r = await client.GetAsync(resourceUrl);
The following are, by the way, equivalent:
client.DefaultRequestHeaders.Add("Authorization", result.CreateAuthorizationHeader());
or
string accessToken = result.AccessToken;
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
or
string accessToken = result.AccessToken;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
One of the Web API you might want to call is the Microsoft Graph. Although you can always do it by calling the Rest call yourself with an HttpClient, you might want to use the Microsoft Graph .NET API (See https://www.nuget.org/packages/Microsoft.Graph) There are many samples on how to do that with MSAL.NET (See the samples in the GitHub MicrosoftGraph organization containing the string csharp). This is also possible with ADAL.NET. Here is for instance some minimal code doing so:
public class Config
{
// STS
public string Authority { get; set; } = "https://login.microsoftonline.com/microsoft.com";
// Resource to access
public string Resource { get; set; } = "https://graph.microsoft.com";
// Application
public string ClientID { get; set; } = "b391c547-acf3-4bb1-b4d7-f8df005a37df";
public string ReturnUri { get; set; } = "https://MyTutorial";
}
class Program
{
static void Main(string[] args)
{
Config config = new Config();
QueryGraph(config).Wait();
}
private static async Task QueryGraph(Config config)
{
AdalNaiveAuthenticationProvider adalNaiveAuthenticationProvider = new AdalNaiveAuthenticationProvider(config);
GraphServiceClient graph = new GraphServiceClient(adalNaiveAuthenticationProvider);
User me = await graph.Me.Request().GetAsync();
. . .
}
And here is authentication code, leveraging ADAL.NET:
public class AdalNaiveAuthenticationProvider : IAuthenticationProvider
{
public AdalNaiveAuthenticationProvider(Config config)
{
this.config = config;
authenticationContext = new AuthenticationContext(config.Authority);
}
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
{
AuthenticationResult result;
// oversimplified code
result = await authenticationContext.AcquireTokenAsync(config.Resource, config.ClientID,
new Uri(config.ReturnUri),
new PlatformParameters(PromptBehavior.Auto));
request.Headers.Add("Authorization", result.CreateAuthorizationHeader());
}
AuthenticationContext authenticationContext;
Config config;
}
Note that this code authentication code is oversimplified (it systematically has the user sign-in, does not benefit from a cache, and does not do any error handling). We'll see in more details how to write enterprise ready code in other topics
- Home
- Why use ADAL.NET?
- Register your app with AAD
- AuthenticationContext
- Acquiring Tokens
- Calling a protected API
- Acquiring a token interactively
- Acquiring tokens silently
- Using Device Code Flow
- Using Embedded Webview and System Browser in ADAL.NET and MSAL.NET
- With no user
- In the name of a user
- on behalf of (Service to service calls)
- by authorization code (Web Apps)
- Use async controller actions
- Exception types
- using Broker on iOS and Android
- Logging
- Token Cache serialization
- User management
- Using ADAL with a proxy
- Authentication context in multi-tenant scenarios
- Troubleshooting MFA in a WebApp or Web API
- Provide your own HttpClient
- iOS Keychain Access