liveBook · Manning

AddSecurityRequirement

As explained in ASP.NET Core in Action, 3e

AddSecurityRequirement is a Swashbuckle configuration method that declares the security schemes required by an API or its operations.

AddSecurityRequirement declares which authentication scheme an API or its operations require in the OpenAPI document. Paired with AddSecurityDefinition(), it tells Swagger UI that the API is protected. section 25.5

Configure bearer authentication in a small Swashbuckle setup:

  • Define the bearer security scheme with AddSecurityDefinition(). section 25.5
  • Apply AddSecurityRequirement() to declare that the whole API is protected; configure it conditionally when anonymous endpoints are needed. section 25.5

Authorize requests in Swagger UI

After the requirement is configured, Swagger UI displays an Authorize button. Enter Bearer <token>, including the space and prefix. Swagger UI saves the value and attaches it to subsequent requests in the Authorization header. section 25.5

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains scheme definition, requirement declaration, token entry, and request attachment, but not the complete conditional configuration.
Examples
Uses a JWT bearer API, an Authorize dialog, and a Bearer token copied into the Authorization header.
What it assumes
Assumes an API using authentication and authorization, while introducing OpenAPI security scheme configuration from the setup.
What you can do after
Operate Swagger UI by entering a bearer token and sending authorized requests to protected endpoints.
How it connects
Connects OpenAPI security schemes, AddSecurityDefinition, JWT bearer authentication, authorization, and Swagger UI.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.