Question
Set the Authorization Header with WinRT HttpClient and OAuth Tokens
Question
I am using HttpClient to call a REST API and need to send the access token returned by an OAuth request in the Authorization header. I found this .NET-style example:
httpClient.DefaultRequestHeaders.Authorization = new Credential(OAuth.token);
However, the Credential class is not available in WinRT. How can I correctly set the Authorization header with an OAuth token when using WinRT HttpClient?
Short Answer
You will learn that an OAuth token is normally sent as an HTTP authorization scheme plus a token value, such as Bearer <token>. In WinRT, use HttpCredentialsHeaderValue to construct this typed header value and assign it to DefaultRequestHeaders.Authorization or to one individual request.
Concept
An HTTP Authorization header tells a server how the client is authenticating a request. Its usual structure is:
Authorization: <scheme> <credentials>
For an OAuth 2.0 access token, the scheme is commonly Bearer:
Authorization: Bearer eyJhbGciOi...
In WinRT, HttpClient is commonly provided by the Windows.Web.Http namespace. Its headers use WinRT-specific typed classes. The class for the Authorization header is:
Windows.Web.Http.Headers.HttpCredentialsHeaderValue
Credential is not the right type for this job. A credential object generally represents user credentials, such as a username and password, while an OAuth access token is a value placed in a specifically formatted HTTP header.
Using the typed header class is preferable to manually formatting the header because it makes the header's scheme and parameter explicit.
Mental Model
Think of an API request as entering a secure building:
- The Authorization header is the security desk information.
Beareris the type of pass you are presenting.- The OAuth access token is the unique pass number.
The server expects both pieces in the correct order: Bearer followed by the token. Sending only the token is like giving security a pass number without saying what kind of pass it is.
Syntax and Examples
Import the WinRT HTTP namespaces:
using Windows.Web.Http;
using Windows.Web.Http.Headers;
Set an OAuth Bearer token for all requests made by one HttpClient instance:
var httpClient = new HttpClient();
string accessToken = OAuth.token;
httpClient.DefaultRequestHeaders.Authorization =
new HttpCredentialsHeaderValue("Bearer", accessToken);
This produces a request header equivalent to:
Authorization: Bearer <accessToken>
Then make requests normally:
HttpResponseMessage response = await httpClient.GetAsync(
new Uri("https://api.example.com/profile"));
The authorization scheme is not always Bearer. Follow the API documentation. For example, an API might require a different scheme:
httpClient.DefaultRequestHeaders.Authorization =
new HttpCredentialsHeaderValue("Token", accessToken);
For standard OAuth 2.0 access tokens, Bearer is the common choice.
Step by Step Execution
Consider this example:
var client = new HttpClient();
string token = "abc123";
client.DefaultRequestHeaders.Authorization =
new HttpCredentialsHeaderValue("Bearer", token);
HttpResponseMessage response = await client.GetAsync(
new Uri("https://api.example.com/orders"));
-
new HttpClient()creates a client that can send HTTP requests. -
tokenstores the access token obtained from the OAuth authorization flow. -
new HttpCredentialsHeaderValue("Bearer", token)creates a structured authorization value with:- scheme:
Bearer - credentials:
abc123
- scheme:
-
Assigning it to
DefaultRequestHeaders.Authorizationmakes it a default header for requests sent throughclient. -
GetAsyncsends a GET request to the orders endpoint. -
The outgoing request includes:
Authorization: Bearer abc123 -
The server validates the token and either returns the protected resource or responds with an authorization error such as
401 Unauthorized.
Real World Use Cases
OAuth authorization headers are used whenever an application calls a protected API on behalf of a user or application.
- Mobile applications: Send a signed-in user's access token while loading their profile or messages.
- REST API clients: Authenticate calls to endpoints such as
/orders,/files, or/calendar/events. - Background synchronization: Use an application or user token to sync data on a schedule.
- Cloud services: Call services that protect resources with OAuth 2.0 access tokens.
- Desktop applications: Add a token after a login flow before calling the application's backend API.
Use HTTPS for token-bearing requests. An access token can grant access to protected resources, so it must not be exposed over an insecure connection.
Real Codebase Usage
In real applications, developers usually avoid scattering header setup across every API call. Instead, they centralize it in an API client or a method that creates authenticated requests.
Set a default header for a short-lived, user-specific client
public HttpClient CreateAuthenticatedClient(string accessToken)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new HttpCredentialsHeaderValue("Bearer", accessToken);
return client;
}
Set the header on one request
A per-request header is useful when different requests use different tokens or when a client also makes public requests.
var request = new HttpRequestMessage(
HttpMethod.Get,
new Uri("https://api.example.com/profile"));
request.Headers.Authorization =
new HttpCredentialsHeaderValue("Bearer", accessToken);
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
Validate before sending
Use a guard clause so that code does not send an invalid authorization value:
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new InvalidOperationException("An access token is required.");
}
Handle expired tokens
A 401 Unauthorized response can mean the token is missing, invalid, or expired. Production code commonly refreshes the token through the appropriate OAuth flow, stores the replacement securely, and retries only when it is safe to do so.
Common Mistakes
Using a nonexistent or incorrect credential type
This does not represent a WinRT authorization header:
// Incorrect for WinRT HttpClient authorization headers
httpClient.DefaultRequestHeaders.Authorization = new Credential(accessToken);
Use HttpCredentialsHeaderValue instead:
httpClient.DefaultRequestHeaders.Authorization =
new HttpCredentialsHeaderValue("Bearer", accessToken);
Omitting the authorization scheme
This is incomplete for APIs that expect Bearer authentication:
// Incorrect: the server cannot identify the token scheme.
httpClient.DefaultRequestHeaders.TryAppendWithoutValidation(
"Authorization",
accessToken);
Include both the scheme and token:
new HttpCredentialsHeaderValue("Bearer", accessToken)
Putting Bearer inside the token parameter
Do not duplicate the scheme:
// Incorrect: becomes "Bearer Bearer abc123"
new HttpCredentialsHeaderValue("Bearer", "Bearer abc123");
Pass only the raw token as the second argument:
new HttpCredentialsHeaderValue("Bearer", "abc123");
Using the wrong API namespace
There are different HttpClient APIs in .NET and WinRT. Make sure the header value class matches the client you use:
- WinRT:
Windows.Web.Http.Headers.HttpCredentialsHeaderValue - Modern .NET:
System.Net.Http.Headers.AuthenticationHeaderValue
Logging tokens
Avoid printing authorization headers or full access tokens to logs, crash reports, or the console. Treat access tokens as secrets.
Assuming every authentication method is Bearer
OAuth 2.0 APIs commonly use Bearer, but the server documentation is authoritative. Do not invent the scheme name.
Comparisons
| Situation | WinRT API | Modern .NET API | Typical use |
|---|---|---|---|
| Set an OAuth Authorization header | new HttpCredentialsHeaderValue("Bearer", token) | new AuthenticationHeaderValue("Bearer", token) | Send an access token to a protected API |
| Apply header to every client request | client.DefaultRequestHeaders.Authorization | client.DefaultRequestHeaders.Authorization | One client uses one identity/token |
| Apply header to one request | request.Headers.Authorization | request.Headers.Authorization | Different requests need different tokens |
| Send username/password credentials | Depends on the protocol and API | Depends on the protocol and API | Different from sending a Bearer access token |
DefaultRequestHeaders are convenient when all requests from a client should have the same authorization. A request-specific header is safer when authorization differs by request.
Cheat Sheet
using Windows.Web.Http;
using Windows.Web.Http.Headers;
Default header for a WinRT client
client.DefaultRequestHeaders.Authorization =
new HttpCredentialsHeaderValue("Bearer", accessToken);
Header for one WinRT request
request.Headers.Authorization =
new HttpCredentialsHeaderValue("Bearer", accessToken);
Header sent
Authorization: Bearer <access-token>
Rules
- Use
HttpCredentialsHeaderValuewith WinRTWindows.Web.Http.HttpClient. - Use
Beareronly when the API specifies Bearer authentication. - Pass the raw token as the second argument; do not include
Bearertwice. - Use HTTPS.
- Do not log or hard-code real access tokens.
- Handle
401 Unauthorizedas a possible missing, invalid, or expired token.
FAQ
How do I add a Bearer token to a WinRT HttpClient?
Assign a HttpCredentialsHeaderValue to the Authorization header:
client.DefaultRequestHeaders.Authorization =
new HttpCredentialsHeaderValue("Bearer", accessToken);
What namespace contains HttpCredentialsHeaderValue?
Use:
using Windows.Web.Http.Headers;
It is used with WinRT's Windows.Web.Http.HttpClient.
Is Credential the correct class for an OAuth access token?
No. An OAuth access token is normally sent in an Authorization header with a scheme such as Bearer. In WinRT, represent it with HttpCredentialsHeaderValue.
Should I include Bearer in the token string?
No. Provide Bearer as the first argument and the raw token as the second argument.
new HttpCredentialsHeaderValue("Bearer", accessToken)
Should I use default headers or request headers?
Use DefaultRequestHeaders when every request from that client uses the same token. Set request.Headers.Authorization when only one request needs the token or tokens vary between requests.
What does a 401 response mean after adding the header?
It commonly means the token is missing, invalid, expired, or lacks access to the requested resource. Check the API response and OAuth token lifecycle.
What is the equivalent in modern .NET?
For System.Net.Http.HttpClient, use System.Net.Http.Headers.AuthenticationHeaderValue rather than WinRT's HttpCredentialsHeaderValue.
Mini Project
Description
Build a small WinRT API client that sends an OAuth Bearer token while requesting a protected profile endpoint. The example demonstrates validation, setting a typed Authorization header, and checking the HTTP response.
Goal
Send an authenticated GET request and return the profile response body only when the server reports success.
Requirements
- Accept an OAuth access token as a method argument.
- Reject missing or whitespace-only tokens before sending a request.
- Send the token using the Bearer authorization scheme.
- Request a protected profile endpoint over HTTPS.
- Return the response body for successful responses.
- Throw a useful error when the request fails.
Keep learning
Related questions
AddTransient vs AddScoped vs AddSingleton in ASP.NET Core Dependency Injection
Learn the differences between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI with examples and practical usage.
Best Way to Repeat a Character in C#: Building Repeated Strings Efficiently
Learn the best way to repeat a character in C#, compare StringBuilder, string concatenation, and simpler built-in options.
C# Access Modifiers and static: public, private, protected, and Defaults
Learn how C# public, private, protected, and default access control visibility, and how static differs from instance members.