We have have a Spring 5, non-Spring Boot application, using Springfox 2.9.2 + Swagger UI.
I don't know how to secure /api-docs endpoint: I'd like it to call my authentication function each time it's accessed. I made it work for swagger-ui.html, but without success for /api-docs. Here's what I got.
@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig implements WebMvcConfigurer {
@Autowired
protected AuthService authService;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// registry.addViewController("/docs/swagger/api-docs"); doesnt work
registry.addRedirectViewController("/docs/swagger/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui");
registry.addRedirectViewController("/docs/swagger/swagger-resources/configuration/security", "/swagger-resources/configuration/security");
registry.addRedirectViewController("/docs/swagger/swagger-resources", "/swagger-resources");
}
class Interceptor implements HandlerInterceptor{
@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler ) {
try{
authService.assertAdmin(); // I need to call this
}catch (Exception e){
return false;
}
return true;
}
}
@Override
public void addInterceptors( final InterceptorRegistry registry) {
registry.addInterceptor(new Interceptor());
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// docs/swagger/index.html
registry.addResourceHandler("/docs/swagger/swagger-ui.html**")
.addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
// docs/swagger/webjars
registry.addResourceHandler("/docs/swagger/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
Another option would be to close access to /api-docs permanently and just directly call the method that generates JSON from some new endpoint. Would that be possible?
Spring-Securityto secure the endpoints? - UsamaAmjad