← All blogs

FullStack Engineering CourseLesson 12 of 20 20 min

Identity and Security: OAuth, JWT, Entra ID, Access Control and OWASP

Authentication and authorisation

Two words are easy to mix up:

  • Authentication (AuthN) answers "who are you?". A user signs in, or a service proves its identity.
  • Authorisation (AuthZ) answers "what are you allowed to do?". Can this biller approve this claim, for this hospital?

Modern systems hand authentication to an identity provider (IdP), such as Microsoft Entra ID, Okta or Auth0, instead of storing passwords themselves. The IdP signs users in (with MFA), issues tokens, and the APIs check those tokens. Authorisation stays in your system, because only your system knows the business rules.

OAuth 2.0 and OpenID Connect

OAuth 2.0 is a standard for giving an application limited access to an API without sharing passwords. OpenID Connect (OIDC) adds a standard way to sign users in on top of OAuth 2.0. The parties involved:

  • Resource owner: the user who owns the data.
  • Client: the application that wants access (a React app, a mobile app, a backend service).
  • Authorisation server: the identity provider that signs the user in and issues tokens (Entra ID).
  • Resource server: the API that holds the data and checks the tokens (your Claims API).

Three kinds of token:

TokenPurposeWho reads itTypical lifetime
Access tokenProves the caller may call an API, with which permissionsThe APIShort: about 1 hour
ID token (OIDC)Tells the client who signed inThe client only, never sent to APIsShort
Refresh tokenGets new access tokens without signing in againThe authorisation serverLong: hours to days; rotated on each use

OAuth defines several flows (ways to get a token). Two cover almost every modern case:

  • Authorization code with PKCE: for anything a user signs in to, including web apps, single-page apps and mobile apps.
  • Client credentials: for a service calling another service with no user involved, such as a nightly job calling the Claims API.

The authorization code flow with PKCE works like this:

  1. The app creates a random secret (the code verifier) and sends a hash of it (the code challenge) when it redirects the user to the identity provider.
  2. The user signs in at the identity provider (with MFA), not in your app, so your app never sees the password.
  3. The identity provider redirects back to the app with a short-lived authorisation code.
  4. The app exchanges the code, together with the original code verifier, for tokens.
  5. The identity provider checks that the verifier matches the challenge, so a code stolen on the way back is useless to an attacker. That check is what PKCE (Proof Key for Code Exchange) adds.

Older flows are no longer recommended. The implicit flow (tokens returned directly in the browser URL) and the password flow (the app collects the user's password) are both deprecated in current OAuth guidance.

SSO (single sign-on) lets a user sign in once and reach many applications. In enterprises it often uses SAML, an older XML-based standard that many business applications still support; new applications should use OIDC. MFA (multi-factor authentication) requires a second proof, such as an authenticator app, and stops most account takeovers that use stolen passwords.

JSON Web Tokens (JWT)

Access tokens are usually JWTs: three base64url parts separated by dots, header.payload.signature. The payload holds claims (statements about the caller):

JSON
{
  "iss": "https://login.microsoftonline.com/7f3c.../v2.0",   // issuer: who created the token
  "aud": "api://claims-api",                                  // audience: which API it is for
  "sub": "a8d1...",                                           // subject: the user or app
  "exp": 1795120000,                                          // expiry (Unix time)
  "scp": "claims.read claims.write",                          // scopes delegated by the user
  "roles": ["Claims.Approver"],                               // app roles assigned to the user
  "tid": "7f3c..."                                            // the Entra tenant
}

The signature lets the API check that the token came from the identity provider and was not changed, using the provider's public keys. Important facts about JWTs:

  • The payload is only encoded, not encrypted. Anyone holding the token can read it, so never put secrets or sensitive data in it.
  • The API must validate the signature, the issuer, the audience and the expiry on every request. A token issued for another API must be rejected.
  • A JWT cannot easily be revoked before it expires, because APIs check it without calling the identity provider. Keep access tokens short-lived, and revoke the refresh token to cut off access.
C#
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.Authority = "https://login.microsoftonline.com/<tenant-id>/v2.0";   // public keys and issuer come from here
        o.Audience = "api://claims-api";                                       // reject tokens meant for other APIs
        o.MapInboundClaims = false;                                            // keep claim names as "scp" and "roles"
        o.TokenValidationParameters.RoleClaimType = "roles";
        o.TokenValidationParameters.ClockSkew = TimeSpan.FromMinutes(1);       // default tolerance is 5 minutes
    });

builder.Services.AddAuthorizationBuilder()
    .AddPolicy("ClaimsRead", p => p.RequireClaim("scp", "claims.read"))
    .AddPolicy("ClaimsApprover", p => p.RequireRole("Claims.Approver"));

app.UseAuthentication();
app.UseAuthorization();

claims.MapGet("/{id:int}", GetClaim).RequireAuthorization("ClaimsRead");
claims.MapPost("/{id:int}/approve", ApproveClaim).RequireAuthorization("ClaimsApprover");

With Entra ID, the Microsoft.Identity.Web package (AddMicrosoftIdentityWebApi) does this setup from configuration and adds helpers for calling other APIs on behalf of the user.

Microsoft Entra ID and managed identities

In Entra ID, each application has an app registration that defines what it is and what it exposes:

  • Scopes (delegated permissions): what a client may do on behalf of a signed-in user, such as claims.read. They appear in the scp claim.
  • App roles: roles assigned to users, groups or applications, such as Claims.Approver. They appear in the roles claim.

Services also need identities, to call databases, Key Vault and other APIs. The old way was a client secret or certificate stored in configuration, which can leak and must be rotated. A managed identity is an identity that Azure creates for a resource (an App Service, a Function, a container) and manages for you. The code gets tokens without any secret existing anywhere:

C#
// DefaultAzureCredential uses the managed identity in Azure, and your developer login (Visual Studio, Azure CLI) locally.
var credential = new DefaultAzureCredential();

var secrets = new SecretClient(new Uri("https://claims-kv.vault.azure.net/"), credential);
var bus = new ServiceBusClient("claims-bus.servicebus.windows.net", credential);
var blobs = new BlobServiceClient(new Uri("https://claimsfiles.blob.core.windows.net/"), credential);
// Azure SQL: "Server=...;Database=...;Authentication=Active Directory Default" in the connection string.

Grant each managed identity only the roles it needs on each resource (Key Vault Secrets User, Service Bus Data Sender), never broad Owner or Contributor roles. For things running outside Azure, such as GitHub Actions or Kubernetes, workload identity federation lets them get Entra tokens by trusting their own identity tokens, again with no stored secret.

Authorisation models: RBAC, ABAC and ReBAC

ModelDecides access byExampleStrengthsLimits
RBAC (role-based)The user's rolesApprovers may approve claimsSimple, easy to auditRoles multiply when rules depend on data ("approver for hospital X under 10,000")
ABAC (attribute-based)Attributes of the user, the resource, the action and the contextApprove if the user's region equals the claim's region and the amount is under the user's limitFine-grained rules without endless rolesRules can become hard to understand and audit
ReBAC (relationship-based)Relationships between the user and the resourceA user can view a claim if they are assigned to it, or belong to the hospital that owns itNatural for sharing, hierarchies and organisations; scales to huge numbers of objectsNeeds a relationship store and a dedicated service

In ASP.NET Core, policies cover RBAC and simple ABAC. When the decision depends on the specific resource (this claim's tenant, this claim's amount), load the resource first and use resource-based authorisation:

C#
public sealed record ApproveRequirement : IAuthorizationRequirement;

public sealed class ApproveClaimHandler : AuthorizationHandler<ApproveRequirement, ClaimRecord>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                   ApproveRequirement requirement, ClaimRecord claim)
    {
        bool sameTenant = context.User.FindFirstValue("tenant_id") == claim.TenantId.ToString();
        bool isApprover = context.User.IsInRole("Claims.Approver");
        bool withinLimit = decimal.TryParse(context.User.FindFirstValue("approval_limit"), out var limit)
                           && claim.Amount <= limit;

        if (sameTenant && isApprover && withinLimit)
            context.Succeed(requirement);
        return Task.CompletedTask;
    }
}

// builder.Services.AddSingleton<IAuthorizationHandler, ApproveClaimHandler>();
// builder.Services.AddAuthorizationBuilder().AddPolicy("ApproveClaim", p => p.AddRequirements(new ApproveRequirement()));

static async Task<IResult> ApproveClaim(int id, ClaimsPrincipal user, IAuthorizationService authz,
                                        IClaimRepository claims, CancellationToken ct)
{
    var claim = await claims.GetAsync(id, ct);
    if (claim is null) return TypedResults.NotFound();

    var result = await authz.AuthorizeAsync(user, claim, "ApproveClaim");
    if (!result.Succeeded) return TypedResults.Forbid();     // 403

    // ... approve
    return TypedResults.NoContent();
}

ReBAC is usually provided by a dedicated authorisation service modelled on Google's Zanzibar system: OpenFGA (and its hosted version, Okta FGA), SpiceDB or Auth0 FGA. You describe the relationships once, write relationship facts ("user:asha is assignee of claim:42") as they happen, and ask the service "can this user do this to this object?" at runtime:

model
  schema 1.1

type user

type organization
  relations
    define member: [user]
    define admin: [user]

type claim
  relations
    define owner_org: [organization]
    define assignee: [user]
    define viewer: assignee or member from owner_org
    define approver: admin from owner_org

Policy engines such as OPA (Open Policy Agent) take another approach: rules are written in a policy language (Rego), kept outside the application code, and evaluated by a separate service or library. This suits organisations that want one consistent, auditable place for rules across many services and platforms.

Whatever the model, a few rules never change:

  • Check authorisation on the server, on every request. Hiding a button in the UI is not security.
  • Deny by default: an endpoint without an explicit policy should not be reachable. A fallback policy that requires an authenticated user is a good start.
  • Check access to the specific object, not only the type of operation. Most real data leaks are a user reading another user's or another tenant's record by changing an ID (called IDOR: insecure direct object reference).

The OWASP Top 10

The OWASP Top 10 is a widely used list of the most critical web application security risks. Below is the 2021 edition, with the main .NET defences; check owasp.org for the latest edition.

RiskWhat it isMain defences in .NET
A01 Broken access controlUsers acting outside their permissions, such as reading other tenants' dataServer-side, deny-by-default authorisation; resource-based checks; tenant filters
A02 Cryptographic failuresSensitive data exposed through weak or missing encryptionTLS everywhere; encryption at rest; never write your own cryptography; keys in Key Vault
A03 InjectionUntrusted input run as code: SQL, commands, scriptsParameterised queries (EF Core does this); never build SQL with string concatenation; encode output
A04 Insecure designSecurity missing from the design itselfThreat modelling (lesson 11); secure defaults; limits on business actions
A05 Security misconfigurationDefault settings, open storage, detailed errors in productionInfrastructure as code; Azure Policy; Problem Details without stack traces; security headers
A06 Vulnerable and outdated componentsLibraries with known vulnerabilitiesDependabot or Renovate; dotnet list package --vulnerable; regular upgrades
A07 Identification and authentication failuresWeak login, session or token handlingUse an identity provider with MFA; short-lived tokens; never build your own login
A08 Software and data integrity failuresUntrusted updates, pipelines or serialised dataSigned packages and images; protected CI/CD; avoid unsafe deserialisation such as BinaryFormatter
A09 Security logging and monitoring failuresAttacks go unnoticedLog authentication and authorisation failures; alert on unusual patterns; keep audit trails
A10 Server-side request forgery (SSRF)The server is tricked into calling internal addressesAllow-list outbound destinations; never fetch URLs supplied by users without checks

mTLS and zero trust

In normal TLS, only the server proves its identity with a certificate. In mutual TLS (mTLS), the client presents a certificate too, so both sides prove who they are before any data is exchanged. It is common for service-to-service traffic and for partner integrations (for example, a payer connecting to your API). A service mesh (such as Istio or Linkerd on Kubernetes) can add mTLS between all services automatically, and Azure API Management and App Service can require client certificates.

Zero trust is a security model built on the idea that no network location is trusted by default, not even inside the company network. Its three principles:

  • Verify explicitly: authenticate and authorise every request, using identity, device and context, not network location.
  • Use least privilege: give each user and service only the access it needs, for only as long as it needs it.
  • Assume breach: design so that one compromised component cannot reach everything. Segment networks, encrypt everything and log everything.

In Azure practice, this means private endpoints for databases, Key Vault and storage (no public access), managed identities instead of secrets, Entra Conditional Access policies (for example, MFA required from unknown devices), and authorisation checks inside every service, even for internal calls.

Secrets and sensitive data

  • Never put secrets in code, configuration files, container images or logs. Keep them in Key Vault and prefer managed identities, so most secrets do not exist at all.
  • Rotate the secrets that remain, and use Key Vault references (lesson on Azure) so applications pick up new values without redeployment.
  • Scan repositories for leaked secrets (GitHub secret scanning or similar), and treat any leaked secret as compromised: revoke it, do not just delete the commit.
  • Encrypt data in transit (TLS 1.2 or later) and at rest (Azure SQL Transparent Data Encryption is on by default). Use Always Encrypted or application-level encryption for the most sensitive columns.
  • Collect and keep only the personal and health data you need (data minimisation), and mask or remove it from logs, traces and non-production environments.
  • For regulated data, such as US patient data under HIPAA, record who accessed which record and when, and keep those audit logs tamper-proof.

Check your understanding

QuestionShort answer
Authentication or authorisation?Authentication proves who you are; authorisation decides what you may do.
Which OAuth flow for a single-page app?Authorization code with PKCE. The implicit flow is deprecated.
Which flow for a service calling another service?Client credentials, ideally using a managed identity instead of a stored secret.
What does PKCE protect against?A stolen authorisation code: it cannot be exchanged without the original code verifier.
ID token or access token for calling an API?The access token. ID tokens are only for the client to learn who signed in.
Is a JWT payload secret?No. It is only encoded; anyone holding the token can read it.
What must an API validate in a JWT?Signature, issuer, audience and expiry, on every request.
What is a managed identity?An identity Azure creates and manages for a resource, so code gets tokens without any stored secret.
RBAC, ABAC or ReBAC?Roles for simple rules, attributes for data-dependent rules, relationships for sharing and organisational hierarchies.
What is IDOR?Accessing another user's object by changing an ID in a request; prevented by checking access to the specific object.
What are the zero trust principles?Verify explicitly, use least privilege, assume breach.
What is mTLS?TLS where both client and server present certificates and verify each other.

Summary

  • Let an identity provider handle sign-in, MFA and tokens; keep business authorisation in your services.
  • Use authorization code with PKCE for users and client credentials for services; avoid implicit and password flows.
  • Validate every JWT fully, keep access tokens short-lived, and never put secrets in them.
  • Use managed identities and workload identity federation instead of stored secrets, with least-privilege roles.
  • Authorise on the server, deny by default, and check access to each specific object; choose RBAC, ABAC or ReBAC by the shape of your rules.
  • Work through the OWASP Top 10, and apply zero trust: private endpoints, mTLS where useful, and checks on every call.
  • Keep secrets in Key Vault, encrypt data, minimise and mask sensitive data, and keep audit trails.

The next lesson covers data: SQL Server and PostgreSQL tuning, indexing, partitioning and sharding, read replicas, connection pooling, change data capture, and EF Core performance.

Found this useful? Share it: LinkedIn X

Comments