springfox icon indicating copy to clipboard operation
springfox copied to clipboard

Cant see authentication button when using basic auth security scheme

Open mrj365 opened this issue 10 years ago • 8 comments

Springfox swagger 2.4.0

Docket:

@Configuration
@EnableSwagger2
public class SwaggerConfig {                                    
    @Bean
    public Docket api() { 

        AuthorizationScope[] authScopes = new AuthorizationScope[1];
        authScopes[0] = new AuthorizationScopeBuilder()
                .scope("read")
                .description("read access")
                .build();
        SecurityReference securityReference = SecurityReference.builder()
                .reference("test")
                .scopes(authScopes)
                .build();

        List<SecurityContext> securityContexts = Arrays.asList((SecurityContext.builder().securityReferences
                (Arrays.asList((securityReference))).build()));     


        return new Docket(DocumentationType.SWAGGER_2)
          .securitySchemes(Arrays.asList((new BasicAuth("test"))))
          .securityContexts(securityContexts)
          .select()
          .apis(RequestHandlerSelectors.any())            
          .paths(PathSelectors.any())          
          .paths(Predicates.not(PathSelectors.ant("/admin/**")))
          .paths(Predicates.not(PathSelectors.ant("/admin.json")))
          .paths(Predicates.not(PathSelectors.ant("/error/**")))
          .paths(Predicates.not(PathSelectors.ant("/exception/**")))
          .build();                    

    }

      @Bean
      SecurityConfiguration security() {
        return new SecurityConfiguration(
            "test-app-client-id",
            "test-app-client-secret",
            "test-app-realm",
            "test-app",
            "apiKey",
            ApiKeyVehicle.HEADER, 
            "api_key", 
            "," /*scope separator*/);
      }
}

Controller interface:

    @ApiOperation(value = "Get Person", response = UserResponse.class,  authorizations = {@Authorization(value="test")})
    @ApiResponses(value = { @ApiResponse(code = 404, message = "Person not found", response=ExceptionResponse.class) })
    ResponseEntity<UserResponse> getPerson(@ApiParam(value="User Id", required=true) @PathVariable("id") int userId);

Relevent json

"/users/{id}":{  
         "get":{  
            "tags":[  
               "user-controller"
            ],
            "summary":"Get Person",
            "operationId":"getPersonUsingGET",
            "consumes":[  
               "application/json"
            ],
            "produces":[  
               "application/json"
            ],
            "parameters":[  
               {  
                  "name":"device-id",
                  "in":"header",
                  "description":"Device ID",
                  "required":true,
                  "type":"ref"
               },
               {  
                  "name":"id",
                  "in":"path",
                  "description":"User Id",
                  "required":true,
                  "type":"integer",
                  "format":"int32"
               }
            ],
            "responses":{  
               "404":{  
                  "description":"Person not found",
                  "schema":{  
                     "$ref":"#/definitions/ExceptionResponse"
                  }
               },
               "200":{  
                  "description":"OK",
                  "schema":{  
                     "$ref":"#/definitions/UserResponse"
                  }
               },
               "401":{  
                  "description":"Unauthorized"
               },
               "403":{  
                  "description":"Forbidden"
               }
            },
            "security":[  
               {  
                  "test":[  

                  ]
               }
            ]
         }
      }
   },
   "securityDefinitions":{  
      "test":{  
         "type":"basic"
      }
   }

image

mrj365 avatar Mar 22 '16 22:03 mrj365

I believe the authentication button only appears for oauth scenarios.

Have you looked at this thread?

dilipkrish avatar Mar 23 '16 01:03 dilipkrish

Same problem for me... For basic authentication I'd like to see login and password instead of api_key like here https://watson-api-explorer.mybluemix.net/apis/tone-analyzer-v3-beta#!/tone/post_v3_tone

Hronom avatar May 01 '16 19:05 Hronom

You'd have to customize swagger ui and use your own version of it to do that.

dilipkrish avatar May 01 '16 19:05 dilipkrish

Any reason why it's not possible to show a login / pass form field to be able to call basic authenticated WS through swagger ui ?!

TehBakker avatar Sep 12 '17 13:09 TehBakker

I followed the above steps to implement the Basic Authentication and I am not able to see the authentication

shpopuri avatar Sep 13 '17 18:09 shpopuri

This is a really old post. Would you mind creating a new issue with additional details @TehBakker & @shpopuri

dilipkrish avatar Sep 14 '17 00:09 dilipkrish

Hi, I managed to use the Authentication button for Basic Auth with username and password together with jwt apiKey for my other Docket().

Here is example of my implementation:

public class SwaggerDocumentationConfig extends WebMvcConfigurerAdapter {
	
	private final String newLineInDescription = "\r\n\r\n";
	
	@Value("${management.context-path}")
	private String actuatorPath;

	private <T> List<T> newArrayList(T something) {
		List<T> list = new ArrayList<T>();
		list.add(something);

		return list;
	}

	private ApiKey apiKey() {
		return new ApiKey("Authorization", "Authorization", "header");
	}

	private SecurityContext securityContext() {
		return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("/api/v1/*"))
				.build();
	}

	List<SecurityReference> defaultAuth() {
		AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
		AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
		authorizationScopes[0] = authorizationScope;
		return newArrayList(new SecurityReference("Authorization", authorizationScopes));
	}

	@Bean
	SecurityConfiguration security() {
		return new SecurityConfiguration(
				null, 
				null, 
				null, // realm Needed for authenticate button to work
				null, // appName Needed for authenticate button to work
				null, // apiKeyValue
				ApiKeyVehicle.HEADER, 
				"Authorization", // apiKeyName
				null
		);
	}

	ApiInfo apiInfo() {
		return new ApiInfoBuilder().title("Loan Management API documentation")
				.description("Com.Test" + newLineInDescription +
						"JWT Token Validity: 05.11.2017" + newLineInDescription +
						"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0aW1lem9uZSI6IiswMzowMCIsInhzcmZUb2tlbiI6IjM0Mjc3YmIxLWMzNzQtNDM2ZC1hY2M3LWRjODU0ZDA0YzM0MiIsImFjdG9ySWQiOiIxMDAwIiwic2Vzc2lvbklkIjoiQzM3ODVEQkEtMkQwOS00ODQ0LUIyNDEtNzJEMUUyRDQxRTBFIiwic2NvcGVzIjpbXSwiaWF0IjoxNTA3MjE1MjI3LCJleHAiOjE1MDk4OTAwMjd9.oMTPDUxxg9BPLypHQ_ngZbBsL3sfoxyKMkp5S-QtnUs")
				.license("").licenseUrl("http://unlicense.org").termsOfServiceUrl("").version("1.0.0")
				.contact(new Contact("", "", "")).build();
	}

	@Bean
	public Docket customImplementationForApiPaths() {
		return new Docket(DocumentationType.SWAGGER_2)
				.groupName("api").select()
				.apis(RequestHandlerSelectors.basePackage("com.test.business.api"))
				.build()
				.directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)
				.directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class)
				.securitySchemes(newArrayList(apiKey())).apiInfo(apiInfo())
				.securityContexts(newArrayList(securityContext()));
	}

	private BasicAuth actuatorBasicAuth() {
		return new BasicAuth("basic");
	}

	private SecurityContext actuatorSecurityContext() {
		return SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex(actuatorPath + "/*"))
				.build();
	}

	List<SecurityReference> actuatorDefaultAuth() {
		AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
		AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
		authorizationScopes[0] = authorizationScope;
		return newArrayList(new SecurityReference("Authorization", authorizationScopes));
	}

	ApiInfo actuatorApiInfo() {
		return new ApiInfoBuilder().title("Loan Management Actuator API documentation")
				.description("Com.Test" + newLineInDescription +
						"username: admin" + newLineInDescription +
						"password: secret")
				.license("").licenseUrl("http://unlicense.org").termsOfServiceUrl("").version("1.0.0")
				.contact(new Contact("", "", "")).build();
	}
	
	@Bean
	public Docket customImplementationForActuatorPaths() {
		return new Docket(DocumentationType.SWAGGER_2)
				.groupName("x-actuator").select()
				.paths(PathSelectors.ant(actuatorPath + "/**"))
				.build()
				.directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)
				.directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class)
				.securitySchemes(newArrayList(actuatorBasicAuth())).apiInfo(actuatorApiInfo())
				.securityContexts(newArrayList(actuatorSecurityContext()));
	}
}

goodlifeinc avatar Oct 17 '17 14:10 goodlifeinc

For me it works for 2.6.1 but not for 2.5.0

miklas-ez avatar Jun 10 '20 10:06 miklas-ez