Swagger not working with JWT authentication in Spring Boot application

61 Views Asked by At

I have enabled Swagger in my Spring Boot application and tested it with two backend setups. The first one does not include user authentication, and all API endpoints are accessible through Swagger. It works correctly in this case. However, in the second application, I have added user authentication. Swagger is not working because it requires a JWT authenticated token for access to the address http://localhost:9000/swagger-ui/index.html.

 @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http.cors().and().csrf(csrf -> csrf.disable())
                .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth.requestMatchers("/auth/**").permitAll()
                        .requestMatchers("/uploads/**").permitAll()
                        .requestMatchers("/swagger-ui/**", "/configuration/**", "/swagger-resources/**",
                                "/v2/api-docs",
                                "/webjars/**")
                        .permitAll()

                        .anyRequest().authenticated()); // "/auth" requests only permits

        http.authenticationProvider(authenticationProvider());

        // Call for the filter function,
        http.addFilterBefore(authenticationJwTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

Is there any other method available to do this?

0

There are 0 best solutions below