0

Currently, swagger-docs are open to public and I would like to hide them behind some auth wall. I am using SpringDoc and API Key auth is the major authentication mechanism this project is using. All the APIs are authenticated by it only. Here is the SecurityConfig

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final ApiKeyAuthenticationProvider apiKeyAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .authorizeRequests()
                .antMatchers("/health").permitAll()
                .antMatchers("/api/**").hasAnyAuthority("DEV", "ADMIN")
                .anyRequest()
                .authenticated()
                .and()
                .csrf().disable()
                .addFilterBefore(
                        new ApiKeyAuthenticationFilter(authenticationManager()),
                        AnonymousAuthenticationFilter.class);

        httpSecurity.exceptionHandling()
                .accessDeniedHandler((request, response, accessDeniedException) -> {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                })
                .authenticationEntryPoint((request, response, authException) -> {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                });
    }

    @Override
    public void configure(WebSecurity web)  {
        web.ignoring().antMatchers(
                "/health"
        );
    }

    @Bean
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(Collections.singletonList(apiKeyAuthenticationProvider));
    }

}

I tried adding /swagger-ui/** to HttpSecurity and then use formLogin() and httpBasic() but it was throwing 401 error.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

0 Answers0