question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to configure BasicAuth for Swagger UI?

See original GitHub issue

Using SpringFox v. 2.9.2 and Spring Security v. 1.4.1.RELEASE

This is a question, and I’m sure is just a mistake in configuration on my end.

I have the following Docket configuration:

	@Bean
	public Docket api() {

		SecurityReference securityReference = SecurityReference.builder()
				.reference("basicAuth")
				.scopes(new AuthorizationScope[0])
				.build();

		ArrayList<SecurityReference> reference = new ArrayList<>(1);
		reference.add(securityReference);

		ArrayList<SecurityContext> securityContexts = new ArrayList<>(1);
		securityContexts.add(SecurityContext.builder().securityReferences(reference).build());

		ArrayList<SecurityScheme> auth = new ArrayList<>(1);
		auth.add(new BasicAuth("basicAuth"));

		return new Docket(DocumentationType.SWAGGER_2)
				.securitySchemes(auth)
				.securityContexts(securityContexts)
				.select()
					.apis(RequestHandlerSelectors.basePackage("com.my.package.directory"))
					.paths(PathSelectors.any())
					.build()
				.apiInfo(getApiInfo());
	}

The following Spring security configuration (defined in boostrap file):

security.user.name=jdoe
security.user.password=123456

When navigation to my swagger page, I see the following UI layout:

image

I am able to access any of the endpoints at this time, and hit them as usual. When selecting the “authorize” button, I get the following UI:

image

On that page, I can enter in literally any combination of username/passwords and it will display the following:

image

And, just like before I logged in, I am able to access any of the endpoints.

My expectation (desire) is that when navigating to the page, none of the endpoints will be usable by the user. They will receive a 401, or the “Try it Out” button will be disabled, until they login. The login credentials should only accept preconfigured combinations (jdoe/123456).

Like I said, I’m sure this is just a misconfiguration on my end, but after a few days of spinning my wheels, digging through documentation and StackOverflow, I’m not sure what I’m missing. Any help or guidance would be appreciated!

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:3
  • Comments:18

github_iconTop GitHub Comments

14reactions
czgabcommented, Sep 24, 2019

I found the solution, also using SpringFox v. 2.9.2, hope it helps.

    @Bean
    public Docket actuatorApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("Spring Actuator")
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.ant("/actuator/**"))
                .build()
                .apiInfo(apiInfo())
                .securityContexts(Arrays.asList(actuatorSecurityContext()))
                .securitySchemes(Arrays.asList(basicAuthScheme()));
    }

    private SecurityContext actuatorSecurityContext() {
        return SecurityContext.builder()
                .securityReferences(Arrays.asList(basicAuthReference()))
                .forPaths(PathSelectors.ant("/actuator/**"))
                .build();
    }

    private SecurityScheme basicAuthScheme() {
        return new BasicAuth("basicAuth");
    }

    private SecurityReference basicAuthReference() {
        return new SecurityReference("basicAuth", new AuthorizationScope[0]);
    }
1reaction
blaqnizcommented, Mar 17, 2020

How do I validate username and password when I have this code:

@Configuration @EnableSwagger2 @Profile({Constants.PROFILE_LOCAL, Constants.PROFILE_UAT}) public class SwaggerConfig {

@Value("${version.number}")
private String version;

@Bean
public Docket api() {

    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
            .paths(PathSelectors.any())
            .build()
            .apiInfo(apiInfo())
            .securitySchemes(Arrays.asList(securityScheme()))
            .securityContexts(Arrays.asList(securityContexts()));
}

private ApiInfo apiInfo() {

    return new ApiInfoBuilder()
            .title("My API")
            .description("My API Documentation")
            .version(version)
            .build();
}

private SecurityContext securityContexts() {
    return SecurityContext.builder()
            .securityReferences(Arrays.asList(basicAuthReference()))
            .forPaths(PathSelectors.any())
            .build();
}

private SecurityScheme securityScheme() {
    return new BasicAuth("basicAuth");
}

private SecurityReference basicAuthReference() {
    return new SecurityReference("basicAuth", new AuthorizationScope[0]);
}

}

At the moment I can login with any credentials and even when I don’t provide any credentials, I can still access the APIS.

image

Read more comments on GitHub >

github_iconTop Results From Across the Web

Basic Authentication - Swagger
The first section, securitySchemes , defines a security scheme named basicAuth (an arbitrary name). This scheme must have type: http and scheme: basic...
Read more >
Adding Basic Authorization for Swagger-UI - Stack Overflow
Swagger UI 3.x. In Swagger UI 3.13.0+, you can use the preauthorizeBasic method to pre-fill the Basic auth username and password for "try...
Read more >
Adding Basic Auth authorization option to OpenAPI/Swagger ...
Authorize button for basic auth. This is a short guide on how to enable Open API/Swagger UI support for Basic Auth.
Read more >
How to authorize Basic Auth requests in Spring Boot Swagger UI
How to configure a Spring Boot app to apply Basic Auth and allow only authenticated users to call your API endpoints in Swagger...
Read more >
How to add basic authentication in swagger UI - Google Groups
How to add basic authentication in swagger UI · 1. I'm configured for it... · 2. If it does not include the authorization...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found