Skip to content

Instantly share code, notes, and snippets.

@yuv4ik
Last active February 3, 2017 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuv4ik/8e41b47d3ad3d54827cac0808cf19e98 to your computer and use it in GitHub Desktop.
Save yuv4ik/8e41b47d3ad3d54827cac0808cf19e98 to your computer and use it in GitHub Desktop.
Adding swagger to asp.net web.api 2 owin
public class AuthTokenDocumentFilter : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
swaggerDoc.paths.Add("/token", new PathItem
{
post = new Operation
{
tags = new List<string> { "Auth" },
consumes = new List<string>
{
"application/x-www-form-urlencoded"
},
parameters = new List<Parameter> {
new Parameter
{
type = "string",
name = "grant_type",
required = true,
@in = "formData",
@default = "password"
},
new Parameter
{
type = "string",
name = "username",
required = false,
@in = "formData"
},
new Parameter
{
type = "string",
name = "password",
required = false,
@in = "formData"
}
}
}
});
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
SwaggerConfig.Register(config);
app.UseWebApi(config);
}
}
public class SwaggerConfig
{
public static void Register(HttpConfiguration httpConfig)
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
httpConfig
.EnableSwagger(c =>
{
// API version definition
c.SingleApiVersion("v1", "AspNetWebAPIOauth2");
// Token
c.ApiKey("Token")
.Description("Bearer token")
.Name("Authorization")
.In("header");
c.DocumentFilter<AuthTokenDocumentFilter>();
})
.EnableSwaggerUi(c =>
{
// If your API supports ApiKey, you can override the default values.
// "apiKeyIn" can either be "query" or "header"
//
c.EnableApiKeySupport("Authorization", "header");
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment