Skip to content

Secure OpenAPI with OAuth2 in ASP.NET Core #49

@danlorb

Description

@danlorb

Secure OpenAPI with OAuth2 in ASP.NET Core

🎯 Summary

  • Goal: Implement access control for the OpenAPI document endpoints (/openapi/*.json) using OAuth2/OIDC to prevent unauthorized scanning of the API structure.
  • Stack: ASP.NET Core 10.0, Microsoft.AspNetCore.OpenApi, Microsoft.Identity.Web, System.Security.Claims

🛠 Roadmap (Pomodoro Tasks)

  • Task 1: Register Authentication and Authorization services in Program.cs using AddMicrosoftIdentityWebAppAuthentication or standard AddJwtBearer.
  • Task 2: Define a dedicated Authorization Policy (e.g., "OpenApiPolicy") that checks for specific scopes, roles, or authenticated status.
  • Task 3: Configure the OpenAPI endpoint mapping using MapOpenApi().RequireAuthorization("OpenApiPolicy") to protect the generated JSON.
  • Task 4: Implement OpenApiOptions configuration to add SecurityScheme (Type: OAuth2) to the document for downstream consumer compatibility.
  • Task 5: Add a global OpenApiSecurityRequirement to the document generator to signal that all operations require the defined OAuth2 scheme.
  • Task 6: Verify middleware execution order to ensure UseAuthentication() and UseAuthorization() are called before mapping endpoints.

🔍 Acceptance Criteria

  • Requesting /openapi/v1.json without a valid Authorization: Bearer <token> header returns a 401 Unauthorized.
  • Requesting /openapi/v1.json with a valid token but insufficient permissions returns a 403 Forbidden.
  • The generated JSON file contains the security and securitySchemes components according to the OpenAPI 3.0/3.1 specification.

⚠️ Constraints & Out-of-Scope

  • No UI: Swagger UI, Scalar, or other visual tools are explicitly out-of-scope.
  • Client Implementation: The logic for the client to obtain the token (Implicit, Code Flow, etc.) is handled by the consumer, not this API.

💡 AI-Suggestions

  • Use Idempotency in policy definitions to ensure the "OpenApiPolicy" can be reused for other management endpoints (like Health Checks) if needed.
  • Consider Environment-based branching: Require strict OAuth2 in Production/Staging but allow AllowAnonymous() in local Development if requested.

📚 Resources

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request
    No fields configured for Feature.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions