Skip to content

OAuth2 and JWT Explained: Secure API Authentication for Beginners

Understand OAuth2, access tokens, JWT structure, client credentials, authentication versus authorization and secure validation in ASP.NET Core.

Client → Authorization Server → Access Token
Client → Resource API (+ Bearer token)
Resource API → Validate token and roles → HTTP response
Illustration: OAuth2 access-token flow

1. Authentication versus authorization

Authentication identifies the caller; authorization defines what the caller is permitted to do. A valid identity or token does not automatically grant every permission. Reader and Editor roles provide a simple illustration.

2. What is OAuth 2.0?

OAuth 2.0 is a framework for granting clients limited access to protected resources. Its roles include resource owner, client, authorization server and resource server. OAuth2 is not itself an authentication protocol for user sign-in; OpenID Connect adds an identity layer.

3. Understanding access tokens

An authorization server issues an access token, which a client presents to the resource server. The token represents a limited authorization and typically expires. An API must verify that the token was intended for it.

4. JWT is a token format

JSON Web Token consists of a header, payload and signature. Not every OAuth access token must use JWT. A signed JWT is generally readable rather than encrypted, so sensitive information should not be placed indiscriminately into claims.

5. Client credentials step by step

A background C# service authenticates to a token endpoint using an approved workload identity and requests a token for the target API. It then sends the bearer token to the resource server. The API validates signature, issuer, audience, expiration and required permissions. Never forward a client’s secret to the business API.

6. An example HTTP request

The bearer token is supplied through the Authorization header. This is only a schematic example, not an actual access token. Anyone possessing a valid bearer token may be able to exercise its permissions until it expires.

GET /api/orders HTTP/1.1
Host: api.example.com
Authorization: Bearer YOUR_ACCESS_TOKEN
Accept: application/json

7. Validating tokens in ASP.NET Core

Microsoft.Identity.Web can configure JWT bearer authentication for Microsoft Entra ID APIs. Configure the tenant and client ID of the protected API. Enforce application roles or policies server-side, for instance through ASP.NET Core RequireRole.

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddAuthorization(options =>
    options.AddPolicy("Reader", policy => policy
        .RequireAuthenticatedUser().RequireRole("Api.Reader")));
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/api/orders", () => Results.Ok(new[] { "ORDER-1001" }))
   .RequireAuthorization("Reader");
app.Run();

8. 401 versus 403

HTTP 401 commonly indicates missing or invalid authentication, an expired token or an incorrect audience. HTTP 403 indicates the caller was authenticated but lacks sufficient authorization for the operation.

9. Security best practices

Use HTTPS, keep secrets out of repositories and use managed identities or certificates for suitable workloads. Enforce least privilege and restrict token audiences. Browser apps cannot safely store confidential client secrets; authorization code with PKCE or a backend pattern is typically appropriate.

10. Practice exercises

Draw the roles of a Business Central-to-.NET integration. Explain why a Microsoft Graph token must not automatically be accepted by your API. Test endpoints with no token, a wrong audience and correct Reader or Editor roles.

Documentation

Microsoft: Client credentials · Microsoft: Access tokens · RFC 7519 JWT

Discussion (0)

No comments yet. Be the first to contribute.

Leave a comment