Introduction
In the previous lessons, we built JWT authentication, access tokens, refresh tokens and endpoint authorization. However, a secure system is not complete when the API validates tokens alone. The client must transmit tokens correctly, renew them in a controlled way when they expire, and browser requests from different origins must be restricted deliberately.
This lesson sends requests from an ASP.NET Core MVC application or another client to a JWT-protected API. We then configure CORS at the origin, HTTP method and header levels. The goal is to make client-to-API communication work without granting unnecessary access.
In an API request, an access token is commonly transmitted in the Authorization header with the Bearer scheme. JWT bearer authentication allows a client to access an API resource by sending this header. ([learn.microsoft.com](https://learn.microsoft.com/en-us/aspnet/core/security/authentication/configure-jwt-bearer-authentication?view=aspnetcore-9.0&utm_source=openai))
1. The secure client-request flow
A typical flow contains these steps:
- The user signs in through the client application.
- The authentication server returns an access token and, when required, a refresh token.
- The client sends the access token in the form
Authorization: Bearer <token>when calling a protected API. - The API validates the token signature, issuer, audience and lifetime.
- When the access token expires, the client requests a new token with the refresh token.
- If renewal fails, the client clears the session and asks the user to sign in again.
Do not place access tokens in URL query strings, log messages or ordinary JSON data. Use HTTPS for token transmission and prefer short-lived access tokens.
The bearer authorization header
GET /api/orders HTTP/1.1
Host: api.example.test
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
Accept: application/jsonAuthentication middleware reads this header on the API side. A missing or invalid token normally results in 401 Unauthorized. A valid identity without sufficient permission normally results in 403 Forbidden.
2. Calling an API from ASP.NET Core MVC
A server-side MVC application can call the API through HttpClient. Using IHttpClientFactory helps manage client lifetimes and centralizes basic HTTP configuration.
Register a named HttpClient
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddHttpClient("OrdersApi", client =>
{
client.BaseAddress = new Uri("https://localhost:7200/");
client.DefaultRequestHeaders.Add("Accept", "application/json");
});In production, load the API address from configuration or a secure configuration provider instead of hard-coding it.
A service that adds the token
public sealed class OrdersApiClient
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IAccessTokenStore _tokenStore;
public OrdersApiClient(
IHttpClientFactory httpClientFactory,
IAccessTokenStore tokenStore)
{
_httpClientFactory = httpClientFactory;
_tokenStore = tokenStore;
}
public async Task<HttpResponseMessage> GetOrdersAsync(
CancellationToken cancellationToken = default)
{
var client = _httpClientFactory.CreateClient("OrdersApi");
var accessToken = await _tokenStore.GetAccessTokenAsync();
using var request = new HttpRequestMessage(
HttpMethod.Get, "api/orders");
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
return await client.SendAsync(request, cancellationToken);
}
}Here, IAccessTokenStore is an application-specific abstraction. Session storage may be acceptable for a demonstration, but distributed applications need a secure shared storage strategy. Persisting an access token as unencrypted database data is not a sound default.
Using the client from a controller
public sealed class OrdersController : Controller
{
private readonly OrdersApiClient _apiClient;
public OrdersController(OrdersApiClient apiClient)
{
_apiClient = apiClient;
}
public async Task<IActionResult> Index(
CancellationToken cancellationToken)
{
using var response = await _apiClient
.GetOrdersAsync(cancellationToken);
if (response.StatusCode == HttpStatusCode.Unauthorized)
return RedirectToAction("Login", "Account");
if (!response.IsSuccessStatusCode)
return Problem("Orders could not be loaded.");
var orders = await response.Content
.ReadFromJsonAsync<IReadOnlyList<OrderViewModel>>(
cancellationToken: cancellationToken);
return View(orders);
}
}The client should not display the API error body directly to users. Show a clear, safe message and write diagnostic details only to a protected logging system.
3. Renewing an expired access token
When access tokens are short-lived, an API call may occasionally return 401. Instead of refreshing blindly after every failure, use a controlled policy.
- Send the original API request with the current access token.
- If the response is
401, call the token endpoint with the refresh token. - If renewal succeeds, retry the original request exactly once.
- If renewal fails, remove the stored tokens and require a new login.
public async Task<HttpResponseMessage> SendWithRefreshAsync(
HttpRequestMessage request,
CancellationToken cancellationToken = default)
{
var client = _httpClientFactory.CreateClient("OrdersApi");
var token = await _tokenStore.GetAccessTokenAsync();
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token);
var response = await client.SendAsync(request, cancellationToken);
if (response.StatusCode != HttpStatusCode.Unauthorized)
return response;
response.Dispose();
var refreshed = await _tokenService.RefreshAsync(
cancellationToken);
if (!refreshed)
return new HttpResponseMessage(
HttpStatusCode.Unauthorized);
using var retry = new HttpRequestMessage(
request.Method, request.RequestUri);
retry.Headers.Authorization =
new AuthenticationHeaderValue(
"Bearer", await _tokenStore.GetAccessTokenAsync());
return await client.SendAsync(retry, cancellationToken);
}In a real application, carefully handle request bodies, stream content and one-time resources before retrying. Also prevent many simultaneous requests from refreshing the same session by using a lock, semaphore or centralized token-renewal service.
4. Browser clients and CORS
CORS defines which browser requests from different origins the server permits. An origin is the combination of scheme, host and port. For example, https://app.example.test and https://api.example.test are different origins.
CORS is not an authentication mechanism. It does not automatically protect the server from attacks; it controls whether a browser may read a cross-origin response. ([learn.microsoft.com](https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-10.0&utm_source=openai))
Create a named policy
const string ClientPolicy = "ClientPolicy";
builder.Services.AddCors(options =>
{
options.AddPolicy(ClientPolicy, policy =>
{
policy.WithOrigins("https://app.example.test")
.WithMethods("GET", "POST", "PUT", "DELETE")
.WithHeaders("Authorization", "Content-Type")
.SetPreflightMaxAge(TimeSpan.FromMinutes(10));
});
});Do not add a trailing slash to the origin in WithOrigins. The comparison between https://app.example.test/ and https://app.example.test may not match as expected. Keep development ports separate from production origins.
Middleware order
var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(ClientPolicy);
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();With endpoint routing, UseCors should generally run after UseRouting and before authorization. This helps CORS headers appear correctly, including on unauthorized responses. ([learn.microsoft.com](https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-10.0&utm_source=openai))
Preflight requests
A browser may first send an OPTIONS preflight request when a request uses a method or header that requires permission, such as a custom Authorization header. The API must allow the requested methods and headers in its CORS policy.
OPTIONS /api/orders HTTP/1.1
Origin: https://app.example.test
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorizationAllowAnyOrigin, AllowAnyMethod and AllowAnyHeader can be convenient during development, but production policies should use known origins, methods and headers whenever possible. If cookies or credentials are involved, do not combine wildcard origins with credentialed requests.
5. Different client types
JavaScript fetch
const response = await fetch("https://localhost:7200/api/orders", {
method: "GET",
headers: {
"Authorization": `Bearer ${accessToken}`,
"Accept": "application/json"
}
});
if (response.status === 401) {
// Run refresh logic in one centralized function.
}Use browser developer tools to verify that the token is not exposed in URLs, HTML or unnecessary logs. Evaluate token storage together with your XSS defense and client architecture. In browser-only applications, long-lived sensitive tokens in JavaScript-accessible storage create additional risk.
Testing with Swagger/OpenAPI
If the Swagger UI is configured for the JWT bearer scheme, use its Authorize action to supply a token. Follow the format expected by that UI because some configurations add the Bearer prefix automatically. Keep test tokens separate from real user tokens.
Common mistakes
- Incorrect origin: A different port or HTTP/HTTPS scheme prevents policy matching.
- Missing Authorization permission: The preflight request fails and the browser blocks the call.
- Incorrect UseCors order: CORS headers may not appear on the expected response.
- Infinite retries after 401: Perform one controlled renewal and retry only once.
- Unnecessary exposure of refresh tokens: Depending on the architecture, consider a BFF or HttpOnly-cookie approach.
- Treating CORS as a firewall: CORS does not prevent curl or server-side clients from reaching the API.
- Logging tokens: Never leave access or refresh tokens in headers, exceptions or debug logs.
Practice exercise
Assume that an API and a separate MVC client are running at https://localhost:7200 and https://localhost:7100.
- Create a named CORS policy that allows only
https://localhost:7100. - Allow the
AuthorizationandAcceptheaders forGET /api/orders. - Register an API client with
IHttpClientFactoryin the MVC application. - Send the access token in the bearer authorization header.
- Run the refresh flow once when the API returns
401. - Inspect the OPTIONS preflight and actual request in the browser Network panel.
- Test disallowed origins, methods and headers.
A correct implementation should allow the protected request from the approved origin, cause the browser to block a disallowed origin, and cause the API to reject an invalid token.
Conclusion
Secure client requests require correct bearer-token transmission, controlled token renewal, safe error handling and a narrowly scoped CORS policy. In MVC applications, HttpClientFactory can centralize API access. In browser clients, origins, methods and headers should be explicitly defined.
As the course continues, monitoring, testing and production operation become increasingly important. Think of CORS as an origin-based permission list and JWT as identity evidence carried with an API request; they solve different problems and must not replace one another.