Dev.to Security πŸ” Cybersecurity πŸ‘ 1 πŸ“– 8 min read

Stop Trusting Every JWT: How I Handle OIDC Claims in My Go Gateway

Building a Secure OIDC Verification Layer in Go Authentication is one of those things every backend engineer has to build, yet we all secretly dread getting wrong. When I started architecting the auth layer for my Go-b

Building a Secure OIDC Verification Layer in Go

Authentication is one of those things every backend engineer has to build, yet we all secretly dread getting wrong. When I started architecting the auth layer for my Go-based API gateway, I knew I was going to use OpenID Connect (OIDC). It is the industry standard β€” how hard could it be?

Turns out, parsing a JWT is trivial. Trusting a JWT is where trapdoors are hiding. If you just decode a token and blindly trust the payload, you are exactly one spoofed payload away from a security incident. I needed a way to dynamically discover my identity provider’s keys, cryptographically verify incoming requests, and strictly enforce the claims my backend actually cares about, like ensuring a user actually owns the email address they claim to.

In this post, I will walk you through how I built the OIDC verification layer for my gateway. We will not just look at the happy path; we will look at why I used interfaces to keep the auth logic mockable, how to avoid blocking network traps during startup, and why an unassuming email_verified flag is your gateway’s best friend.

What You’ll Learn

By the end of this post, you will understand how to:

  • verify OIDC ID tokens in Go
  • use OIDC discovery to fetch provider metadata
  • validate token signatures, issuers, and audiences
  • extract strongly typed claims from JWTs
  • enforce application-specific checks like email_verified
  • keep the verification layer testable with interfaces

High-Level Flow

Before looking at the code, here is the flow this verifier follows:

Client
  |
  | ID Token (JWT)
  v
API Gateway
  |
  | 1. Discover OIDC provider metadata
  | 2. Verify JWT signature
  | 3. Validate issuer and audience
  | 4. Extract claims
  | 5. Enforce application-specific rules
  v
Authenticated User

The complete source code for this example is available on GitHub:

https://github.com/Pixie2468/dearai-backend

The Code

Here is the full implementation:

package auth

import (
    "context"
    "errors"
    "fmt"

    "github.com/coreos/go-oidc/v3/oidc"
)

type TokenVerifier interface {
    Verify(ctx context.Context, tokenString string) (*ExternalClaims, error)
}

type ExternalClaims struct {
    Subject       string `json:"sub"`
    Email         string `json:"email"`
    EmailVerified *bool  `json:"email_verified"`
}

type OIDCVerifier struct {
    verifier *oidc.IDTokenVerifier
}

func NewOIDCVerifier(ctx context.Context, issuer, clientID string) (TokenVerifier, error) {
    if issuer == "" || clientID == "" {
        return nil, errors.New("issuer and clientID are required")
    }

    provider, err := oidc.NewProvider(ctx, issuer)
    if err != nil {
        return nil, fmt.Errorf("failed to discover OIDC configuration: %w", err)
    }

    return &OIDCVerifier{
        verifier: provider.Verifier(&oidc.Config{ClientID: clientID}),
    }, nil
}

func (v *OIDCVerifier) Verify(ctx context.Context, tokenString string) (*ExternalClaims, error) {
    idToken, err := v.verifier.Verify(ctx, tokenString)
    if err != nil {
        return nil, fmt.Errorf("cryptographic token verification failed: %w", err)
    }

    var claims ExternalClaims
    if err := idToken.Claims(&claims); err != nil {
        return nil, fmt.Errorf("failed to unmarshal token claims: %w", err)
    }

    if claims.Subject == "" {
        return nil, errors.New("invalid token: missing 'sub' claim")
    }

    if claims.Email == "" {
        return nil, errors.New("invalid token: missing 'email' claim")
    }

    if claims.EmailVerified == nil || !*claims.EmailVerified {
        return nil, errors.New("invalid token: email address is unverified")
    }

    return &claims, nil
}

Package Imports

import (
    "context"
    "errors"
    "fmt"

    "github.com/coreos/go-oidc/v3/oidc"
)

What this does

The package relies on:

  • context for cancellation and timeout control
  • errors for creating simple error values
  • fmt for wrapping errors with additional context
  • go-oidc for OIDC discovery and token verification

Why it matters

OIDC verification often requires network calls and cryptographic validation. Using context.Context ensures these operations can be cancelled or time-limited when necessary.

Defining the Verification Contract

type TokenVerifier interface {
    Verify(ctx context.Context, tokenString string) (*ExternalClaims, error)
}

What this does

This interface defines a single responsibility:

  • accept a token string
  • verify it
  • return validated claims or an error

Why it matters

Consumers depend on the interface rather than a concrete implementation.

This enables testing without contacting a real identity provider.

For example, another package could provide a mock implementation:

type MockVerifier struct{}

func (m *MockVerifier) Verify(ctx context.Context, token string) (*ExternalClaims, error) {
    return &ExternalClaims{Subject: "123"}, nil
}

This is a classic dependency inversion pattern.

Defining the Expected Claims

type ExternalClaims struct {
    Subject       string `json:"sub"`
    Email         string `json:"email"`
    EmailVerified *bool  `json:"email_verified"`
}

What this does

This struct maps JWT claims into Go fields.

Claim Purpose
sub Stable user identifier
email User’s email address
email_verified Indicates whether the provider verified the email

Why it matters

The sub claim should be treated as the primary identifier because:

  • it is immutable
  • it remains stable even if a user changes their email

In contrast, email is mutable and should not be used as a database primary key.

The Concrete Implementation

type OIDCVerifier struct {
    verifier *oidc.IDTokenVerifier
}

What this does

This struct wraps the verifier provided by the OIDC library.

The package exposes the interface:

TokenVerifier

while hiding the implementation details inside:

OIDCVerifier

Why it matters

Consumers only need to know how to call:

Verify(...)

They do not need to know anything about the underlying OIDC library.

This reduces coupling.

Creating a Verifier

func NewOIDCVerifier(ctx context.Context, issuer, clientID string) (TokenVerifier, error) {
    if issuer == "" || clientID == "" {
        return nil, errors.New("issuer and clientID are required")
    }

What this does

Before any network activity occurs, the constructor validates its inputs.

Why it matters

Failing fast prevents confusing runtime errors later.

For example:

NewOIDCVerifier(ctx, "", "")

will immediately return a meaningful error.

OIDC Discovery

// Network I/O occurs here. Ensure ctx has a reasonable timeout.
provider, err := oidc.NewProvider(ctx, issuer)
if err != nil {
    return nil, fmt.Errorf("failed to discover OIDC configuration: %w", err)
}

What this does

The verifier performs OIDC discovery against the issuer.

Typically, this fetches metadata from:

https://issuer/.well-known/openid-configuration

The provider metadata contains information such as:

  • JWKS endpoint
  • authorization endpoint
  • token endpoint
  • supported algorithms

Why it matters

This is the only place in the package where network I/O occurs.

The comment is important:

Ensure ctx has a reasonable timeout.

Without a timeout, application startup could block indefinitely if the issuer is unreachable.

A common pattern is:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

How Signature Verification Works

One of the biggest advantages of OIDC is that your application does not need to manually manage signing keys.

During discovery, the provider exposes a JWKS (JSON Web Key Set) endpoint. The verifier uses those public keys to validate JWT signatures.

This means:

  • signing keys can rotate without application changes
  • compromised keys can be revoked
  • verification remains cryptographically secure

The go-oidc library handles this process automatically.

Building the Token Verifier

return &OIDCVerifier{
    verifier: provider.Verifier(&oidc.Config{ClientID: clientID}),
}, nil

What this does

The discovered provider creates an IDTokenVerifier.

The verifier is configured to validate:

  • JWT signatures
  • token issuer
  • audience (clientID)

Why it matters

Audience validation prevents tokens issued for another application from being accepted by your service.

Token Verification Flow

The core authentication logic lives here.

func (v *OIDCVerifier) Verify(ctx context.Context, tokenString string) (*ExternalClaims, error) {

This method receives a raw JWT and returns validated claims.

Cryptographic Validation

idToken, err := v.verifier.Verify(ctx, tokenString)
if err != nil {
    return nil, fmt.Errorf("cryptographic token verification failed: %w", err)
}

What this does

The OIDC library verifies:

  • signature validity
  • issuer
  • audience
  • expiration
  • other standard token requirements

Why it matters

This step establishes trust in the token.

If verification fails, the method stops immediately.

No claims are processed until the token is proven authentic.

Extracting Claims

var claims ExternalClaims
if err := idToken.Claims(&claims); err != nil {
    return nil, fmt.Errorf("failed to unmarshal token claims: %w", err)
}

What this does

The JWT payload is decoded into the ExternalClaims struct.

For example:

{
  "sub": "abc123",
  "email": "[email protected]",
  "email_verified": true
}

becomes:

ExternalClaims{
    Subject:       "abc123",
    Email:         "[email protected]",
    EmailVerified: &true,
}

Why it matters

From this point onward, the application can work with strongly typed Go values instead of raw JSON.

Validating the Subject Claim

if claims.Subject == "" {
    return nil, errors.New("invalid token: missing 'sub' claim")
}

What this does

Ensures the token contains a non-empty subject identifier.

Why it matters

The subject is the canonical identity of the user.

Without it:

  • user records cannot be linked reliably
  • account ownership becomes ambiguous

This is a critical security check.

Validating the Email Claim

if claims.Email == "" {
    return nil, errors.New("invalid token: missing 'email' claim")
}

What this does

Requires the token to include an email address.

Why it matters

Many applications depend on email for:

  • user profiles
  • notifications
  • login display information

The verifier enforces that requirement up front.

Enforcing Email Verification

if claims.EmailVerified == nil || !*claims.EmailVerified {
    return nil, errors.New("invalid token: email address is unverified")
}

What this does

This check handles two cases:

  1. The claim is missing entirely
   claims.EmailVerified == nil
  1. The claim exists but is false
   !*claims.EmailVerified

Why it matters

A token containing:

{
  "email": "[email protected]",
  "email_verified": false
}

would be rejected.

Likewise, a token omitting the claim completely would also be rejected.

Using a pointer:

*bool

allows the code to distinguish between:

  • false
  • missing claim

which is often important for security-sensitive validation.

ID Tokens vs Access Tokens

This implementation verifies OIDC ID tokens.

ID tokens are designed to identify a user and contain identity-related claims such as:

  • sub
  • email
  • email_verified

Access tokens serve a different purpose. They are intended for API authorization and may have different validation requirements depending on the identity provider.

When implementing authentication, make sure you are validating the correct token type for your use case.

Production Considerations

This implementation is intentionally minimal, but in production you should also consider:

  • context timeouts for OIDC discovery
  • structured logging for authentication failures
  • metrics around verification success and failure rates
  • retry strategies during provider outages
  • caching and startup behavior if the identity provider is unavailable
  • rate limiting before expensive verification logic

Returning Validated Claims

return &claims, nil

What this does

Once all checks pass, the verified claims are returned to the caller.

Why it matters

At this point the caller knows:

  • the token signature is valid
  • the issuer is trusted
  • the audience matches
  • the user has a valid subject
  • an email is present
  • the email has been verified by the identity provider

The returned data can be safely used for authentication and account lookup.

Conclusion

Verifying an OIDC token involves much more than decoding a JWT payload.

By leveraging OIDC discovery and the go-oidc library, we can:

  • validate signatures cryptographically
  • verify issuers and audiences
  • extract strongly typed claims
  • enforce application-specific security requirements such as verified email addresses

The result is a verification layer that is secure, testable, and easy to integrate into a larger authentication system.

Further Reading

If you'd like to see the complete implementation or follow along with future backend engineering articles:

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.