Basic Authentication using Swagger UI

Abhishek :

I am trying to develop a spring-boot based rest API service with API documentation through Swagger UI. I want to enable basic authentication via the swagger UI so that the user can only run the API's once he/she authenticates using the Authorize button on swagger UI (by which a "authorization: Basic XYZ header is added to the API Call

At the front end (in the .json file for the Swagger UI I have added basic authentication for all the APIs using the following code (as per the documentation):

"securityDefinitions": {
        "basic_auth": {
            "type": "basic"
        }
    },
    "security": [
        {
            "basic_auth": []
        }
    ]

How should I implement the backend logic for the use case mentioned above (user can only run the API's once he/she authenticates using the Authorize button on swagger UI and it otherwise shows a 401 Error on running the API)

Some documentation or sample code for the same would be helpful

Sifis :

One option is to use the browser pop up authorization.

  1. When you enable basic auth for your spring boot app, swagger ui will automatically use the browser's pop up window in order to use it for basic auth. This means that the browser will keep the credentials for making requests just like when you trying to access a secured GET endpoint until you close it.

Now, let's say you DON'T want to use the above and want swagger-ui for basic authentication as you say, you have to enable auth functionality on swagger-ui and optionally add security exception when accessing swagger-ui url.

  1. To enable the basic auth functionality to swagger UI (with the "Authorize button" in UI) you have to set security Context and Scheme to your Swagger Docket (This is a simplified version):

    @Configuration
    @EnableSwagger2
    public class SwaggerConfig implements WebMvcConfigurer{
    
        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build()
                    .securityContexts(Arrays.asList(securityContext()))
                    .securitySchemes(Arrays.asList(basicAuthScheme()));
       }
    
        private SecurityContext securityContext() {
            return SecurityContext.builder()
                    .securityReferences(Arrays.asList(basicAuthReference()))
                    .forPaths(PathSelectors.ant("/api/v1/**"))
                    .build();
        }
    
        private SecurityScheme basicAuthScheme() {
            return new BasicAuth("basicAuth");
        }
    
        private SecurityReference basicAuthReference() {
            return new SecurityReference("basicAuth", new AuthorizationScope[0]);
        }
    
    }
    

This enables the authorization button in ui. enter image description here

Now you probably want for your users to access the swagger-ui freely and use this button for authorization. To do this you have to exempt swagger for app's basic auth. Part of this configuration is Security config and you have to add following code:

public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {

            http
                .httpBasic()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)   
                .and().authorizeRequests()
                .antMatchers(
                        "/", "/csrf", 
                        "/v2/api-docs", 
                        "/swagger-resources/**",
                        "/swagger-ui.html",
                        "/webjars/**"
                        ).permitAll()
                .anyRequest().authenticated();

    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326056&siteId=1