Token authorization in swagger in ASP.NET

Viewed 141

I am documenting the API of my application through Swagger, which works with validation through a session token, that is, through a username and password a token is generated for a certain time that allows the user to navigate the site. What I need is for swagger to capture this session token and place it in the header of the requests for the rest of the API methods automatically, the only thing I could achieve so far is to pass the token as a parameter, but doing it manually. The idea is to make it automatic. I leave the configuration of SwaggerConfig.cs that I carry for now.

public class SwaggerConfig
{

    public static void Register()
    {

        var thisAssembly = typeof(SwaggerConfig).Assembly;
        GlobalConfiguration.Configuration
            // HABILITAMOS SWAGGER.
            .EnableSwagger(c =>
                {
                    var baseDirectory = AppDomain.CurrentDomain.BaseDirectory + @"\bin\";
                    var commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".xml";
                    var commentsFile = Path.Combine(baseDirectory, commentsFileName);
                    c.SingleApiVersion("v1", "API");
                    c.OperationFilter<AddRequiredHeaderParameter>();
                    c.PrettyPrint();
                    c.ApiKey("apikey")
                        .Description("API Key Authentication")
                        .Name("Bearer")
                        .In("header");
                    c.IgnoreObsoleteActions();
                    c.IgnoreObsoleteProperties();
                    c.DescribeAllEnumsAsStrings();
             .EnableSwaggerUi(c =>
                {   c.DocumentTitle("Documentación API");
                      c.EnableApiKeySupport("apikey", "header");
                });
    }
}

In turn, add a class to validate the application from where it is made on request

public class AddRequiredHeaderParameter : IOperationFilter
{
    public void Apply(Swashbuckle.Swagger.Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (operation.parameters == null)
            operation.parameters = new List<Parameter>();

        operation.parameters.Add(new Parameter
        {
            name = "AuthorizedClient",
            @in = "header",
            type = "intenger",
            description = "Aplicacion",
            required = true,
            @default = axaxax
        });

        operation.parameters.Add(new Parameter
        {
            name = "ClientKey",
            @in = "header",
            type = "string",
            description = "Cliente",
            required = true,
            @default = "bxbxbx"
        });

        operation.parameters.Add(new Parameter
        {
            name = "Authorization",
            @in = "header",
            type = "apikey",
            description = "Token de sesión",
        });
    }
}
0 Answers
Related