Search code examples
springsecurityspring-bootswagger-uiswagger-2.0

Restrict access to Swagger UI


I have swagger UI working with spring-boot. I have a stateless authentication setup for my spring rest api which is restricted based on roles for every api path.

However, I am not sure how can i put <server_url>/swagger-ui.html behind Basic authentication.

UPDATE

I have following websecurity configured via WebSecurityConfig

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            .csrf().disable()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests()
            .antMatchers("/sysadmin/**").hasRole("SYSADMIN")
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/siteadmin/**").hasRole("SITEADMIN")
            .antMatchers("/api/**").hasRole("USER")
            .anyRequest().permitAll();

    // Custom JWT based security filter
    httpSecurity
            .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

}

Solution

  • One suggestion without knowing more about your configuration is from this SO question.

    https://stackoverflow.com/a/24920752/1499549

    With your updated question details here is an example of what you can add:

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers("/sysadmin/**").hasRole("SYSADMIN")
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/siteadmin/**").hasRole("SITEADMIN")
                .antMatchers("/api/**").hasRole("USER")
                // add the specific swagger page to the security
                .antMatchers("/swagger-ui.html").hasRole("USER")
                .anyRequest().permitAll();
    
        // Custom JWT based security filter
        httpSecurity
                .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
    
    }
    

    The problem with this is it only protects the Swagger UI page and not the API specification which is loaded as a .json file from that UI page.

    A better approach is to put the swagger files under a path so that you can just add antMatchers("/swagger/**").hasRole("USER")