Web API How to Add a Header Parameter for All API in Swagger

Web Api How to add a Header parameter for all API in Swagger

Yes you can do it via inheriting from IOperationFilter

You can find the answer on GitHub here: AddRequiredHeaderParameter

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;

public class AddRequiredHeaderParameter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
operation.Parameters = new List<IParameter>();

operation.Parameters.Add(new NonBodyParameter
{
Name = "X-User-Token",
In = "header",
Type = "string",
Required = false
});
}
}

Then you go to your SwaggerConfig.cs file and add the following in the AddSwaggerGen section:

c.OperationFilter<AddRequiredHeaderParameter>();

Rebuild, and enjoy.

swagger-ui: How to add a header-param request to every-api

You can specify parameters on method or class level. If you define the param as class field, then it will be added to all methods of the corresponding endpoint:

@Path("/someendpoint")
public class MyEndpoint {

@HeaderParam("my-header-id")
@Parameter(name = "my-header-id")
String myHeaderId;

@GET
public Response getAll() {return Response.ok().build()}

@GET
@Path("{id}")
public Response someMethod(@PathParam("id") String id) {return Response.ok().build();}
}

How to send custom headers with requests in Swagger UI?

You can add a header parameter to your request, and Swagger-UI will show it as an editable text box:

swagger: "2.0"
info:
version: 1.0.0
title: TaxBlaster
host: taxblaster.com
basePath: /api
schemes:
- http

paths:

/taxFilings/{id}:

get:
parameters:
- name: id
in: path
description: ID of the requested TaxFiling
required: true
type: string
- name: auth
in: header
description: an authorization header
required: true
type: string
responses:
200:
description: Successful response, with a representation of the Tax Filing.
schema:
$ref: "#/definitions/TaxFilingObject"
404:
description: The requested tax filing was not found.

definitions:
TaxFilingObject:
type: object
description: An individual Tax Filing record.
properties:
filingID:
type: string
year:
type: string
period:
type: integer
currency:
type: string
taxpayer:
type: object

Swagger-UI with auth param text box

You can also add a security definition with type apiKey:

swagger: "2.0"
info:
version: 1.0.0
title: TaxBlaster
host: taxblaster.com
basePath: /api
schemes:
- http

securityDefinitions:
api_key:
type: apiKey
name: api_key
in: header
description: Requests should pass an api_key header.

security:
- api_key: []

paths:

/taxFilings/{id}:

get:
parameters:
- name: id
in: path
description: ID of the requested TaxFiling
required: true
type: string

responses:
200:
description: Successful response, with a representation of the Tax Filing.
schema:
$ref: "#/definitions/TaxFilingObject"
404:
description: The requested tax filing was not found.

definitions:
TaxFilingObject:
type: object
description: An individual Tax Filing record.
properties:
filingID:
type: string
year:
type: string
period:
type: integer
currency:
type: string
taxpayer:
type: object

The securityDefinitions object defines security schemes.

The security object (called "security requirements" in Swagger–OpenAPI), applies a security scheme to a given context. In our case, we're applying it to the entire API by declaring the security requirement a top level. We can optionally override it within individual path items and/or methods.

This would be the preferred way to specify your security scheme; and it replaces the header parameter from the first example. Unfortunately, Swagger-UI doesn't offer a text box to control this parameter, at least in my testing so far.

Add a filter for a header in Swagger for ASP .NET Core 3.1

With the latest version of Swashbuckle compatible with ASP.NET Core 3.1 many types have been replaced by equivalent types in the Microsoft.OpenApi.Models namespace. So you shouldn't use anymore types like NonBodyParameter or IParameter. Both of these have been replaced by a single class OpenApiParameter.

Your code should look like this

using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections.Generic;

namespace Intent2.Auth.Utils
{
public class AddRequiredHeaderParameter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{

if (operation.Parameters == null)
operation.Parameters = new List<OpenApiParameter>();

operation.Parameters.Add(new OpenApiParameter()
{
Name = "X-User-Token",
Description = "Access Token",
In = ParameterLocation.Header,
Schema = new OpenApiSchema() { Type = "String" },
Required = true,
Example = new OpenApiString("Tenant ID example")
});
}
}
}

Then in your startup, simply inject SwaggerGen as usual

services.AddSwaggerGen(options =>
{
options.OperationFilter<AddRequiredHeaderParameter>();
}

You can even make the Tenant ID coming from the outside like a configuration file for example. To do that, modify your AddRequiredHeaderParameter as follow

using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;

namespace Intent2.Auth.Utils
{
public class AddRequiredHeaderParameter : IOperationFilter
{
private string _tenantIdExample;

public AddRequiredHeaderParameter(string tenantIdExample)
{
if (string.IsNullOrEmpty(tenantIdExample ))
throw new ArgumentNullException(nameof(tenantIdExample ));

_tenantIdExample = tenantIdExample;
}

public void Apply(OpenApiOperation operation, OperationFilterContext context)
{

if (operation.Parameters == null)
operation.Parameters = new List<OpenApiParameter>();

operation.Parameters.Add(new OpenApiParameter()
{
Name = "X-User-Token",
Description = "Access Token",
In = ParameterLocation.Header,
Schema = new OpenApiSchema() { Type = "String" },
Required = true,
Example = new OpenApiString(_tenantIdExample)
});
}
}
}

And call it that way from your startup

services.AddSwaggerGen(options =>
{
options.OperationFilter<AddRequiredHeaderParameter>("Tenant ID example");
}

By the way I think if your class is called AddRequiredHeaderParameter you should actually set Required = true instead of false

Add Custom Header in ASP.net core web api (Swashbuckle.AspNetCore -- Version=5.0.0-rc4)

You should register in Startup.cs :

// Startup.cs
services.AddSwaggerGen(c =>
{
...
c.OperationFilter<AuthResponsesOperationFilter>();
};

In addition ,it seems you are passing the Authorization header , according to this and this threads :

The Authorization header parameter defined in /auth/credentials and /system/info won't be used because OpenAPI Specification says that tools should ignore explicit header parameters named Authorization. The Authorization header should be defined as a security scheme instead.



Related Topics



Leave a reply



Submit