Search code examples
asp.netswaggerws-federationswashbuckle

How should I add authentication to swashbuckle?


I am using swashbuckle to add swagger to my asp.net mvc web api project. I see options to add OAuth2, but my website requires wsfederation. How can I require authentication to view the swagger ui with wsfederation?

GlobalConfiguration.Configuration
    .EnableSwagger(c =>
    {
        c.SingleApiVersion("v1", "Services");
    })
    .EnableSwaggerUi(c => { });

Solution

  • Authentication in the SwaggerConfig file is directly linked to documenting your API, and not the actual implementation, so to speak. So if you use the following in your swaggerConfig:

     c.OAuth2("oauth2")
                    .Description("OAuth2 Implicit Grant")
                    .Flow("implicit")
                    .AuthorizationUrl("http://petstore.swagger.io/oauth/dialog")
                    .Scopes(scopes =>
                    {
                        scopes.Add("read:pets", "read your pets");
                        scopes.Add("write:pets", "modify pets in your account");
                    });
    

    That would generate the following securitydefinition in the swagger json file

    securityDefinitions:
      petstore_auth:
        type: oauth2
        authorizationUrl: 'http://petstore.swagger.io/oauth/dialog'
        flow: implicit
        scopes:
          'write:pets': modify pets in your account
          'read:pets': read your pets
    

    To answer

    How can I require authentication to view the swagger ui with wsfederation?

    Just add the authentication globally in the WebApiConfig.cs file, something similar to the following (if you are using a MessageHandler or Filter)

    config.Filters.Add(new WSFederationAuthentication()); 
    

    Viewing the swagger documentation is directly webapi related.

    You might have some issues though, as Swagger gets the docs client side.