How to generate parameters (CORS) with Swagger

For the project we are working on, we automatically create a Swagger. However, at this point we are fighting the CORS part.

We use the API functionality to import Amazon API gateways. To use this in conjunction with Swagger and CORS, we have to create an additional action (operation) in our source code that allows CORS (parameters) for each api (operation)! eg:

    [HttpOptions]
    [Route("{id}")]
    [ProducesResponseType((int)HttpStatusCode.OK)]
    public IActionResult UserOptions()
    {
        return new OkResult();
    }

      

As you can see, this makes the code a lot dirtier. this is a temporary solution, but we cannot find another way. Is there a way to generate this in the swagger definition file automatically? Or how can we do this, Amazon API gateway required this (documentation: http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html )

+3


source to share


2 answers


You can manage your api gateway via x-amazon-apigateway-integration by swagger extension.

Using the Swashbuckle document filter , you can generate a select operation on all of your paths without any corresponding action in your controller.

Here is some sample code that will generate a select operation for all paths in your swagger and add swagger extension extensions to generate layout in the gateway api for these OPTION methods:



    public class AddCorsApiGatewayDocumentFilter : IDocumentFilter
    {
        private Operation BuildCorsOptionOperation()
        {
            var response = new Response
            {
                Description = "Successful operation",
                Headers = new Dictionary<string, Header>
                {
                    { "Access-Control-Allow-Origin", new Header(){Type="string",Description="URI that may access the resource" } },
                    { "Access-Control-Allow-Methods", new Header(){Type="string",Description="Method or methods allowed when accessing the resource" } },
                    { "Access-Control-Allow-Headers", new Header(){Type="string",Description="Used in response to a preflight request to indicate which HTTP headers can be used when making the request." } },
                }
            };
            return new Operation
            {
                Consumes = new List<string> { "application/json" },
                Produces = new List<string> { "application/json" },
                Responses = new Dictionary<string, Response>{{"200",response}}
            };
        }

        private object BuildApiGatewayIntegrationExtension()
        {
            return new
            {
                responses = new
                {
                    @default = new
                    {
                        statusCode = "200",
                        responseParameters = new Dictionary<string, string>
                            {
                                { "method.response.header.Access-Control-Allow-Methods", "'POST,GET,OPTIONS'" },
                                { "method.response.header.Access-Control-Allow-Headers", "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'"},
                                { "method.response.header.Access-Control-Allow-Origin", "'*'"}
                            }
                    },
                },
                passthroughBehavior = "when_no_match",
                requestTemplates = new Dictionary<string, string> { { "application/json", "{\"statusCode\": 200}" } },
                type = "mock"
            };
        }

        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
        {
            foreach (var path in swaggerDoc.Paths)
            {
                var corsOptionOperation = BuildCorsOptionOperation();
                var awsApiGatewayExtension = BuildApiGatewayIntegrationExtension();
                corsOptionOperation.Extensions.Add("x-amazon-apigateway-integration", awsApiGatewayExtension);
                path.Value.Options = corsOptionOperation;
            }
        }
    }

      

Remember to register this filter with swashbuckle:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
            c.DocumentFilter<AddCorsApiGatewayDocumentFilter>();
        });
    }

      

+1


source


Take steps to "Enable CORS" with a simple one-click function in the console, then deploy the API and finally go to the scene and export the API back to swagger.



You can now check swagger to see how to set up CORS in your own swagger.

0


source







All Articles