3

I am aware that swagger-ui can be fully disabled using @Profile on spring-boot application but I still want certain privileged user to be able to access swagger-ui and not fully disabled.

Is there a way to achieve this.

update:

currently I am using interceptor approach but i don't want this approach.

    @Override
public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler) throws Exception {       
    if(request.getRequestURI().contains("swagger") && 
            !request.isUserInRole("XX_YY_ZZ")) {                   

        response.sendError(403, "You are not authorized to access ");            }  
    return super.preHandle(request, response, handler);
}
user9735824
  • 1,196
  • 5
  • 19
  • 36

2 Answers2

2

Without version you use, or codes, it is difficult to help. But I'll try as best as I can.

When you are using swagger-ui, you have an exposed URL to access your docs (usually, /swagger-ui.html). You are using spring-boot, and talking about user restriction, so I assume you can use spring-boot-starter-security. With spring-boot-starter-security, you can configure easily what URL you want to protect (regarding user roles for instance).

Here is a sample configuration that works:

@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // the rest of your configuration
        http.authorizeRequests().mvcMatchers("/swagger-ui.html").hasRole("DEVELOPER")
}

You can secure swagger URLs just like any URLs you expose with your Controllers.

For more information:

I could help more with:

  • An extract of your security configuration
  • The version of Spring-boot you're using
RUARO Thibault
  • 2,672
  • 1
  • 9
  • 14
0

I would suggest adding an interceptor or you can handle it in your exiting interceptor if you have any.

In the spring configuration file:

<mvc:interceptors>
    <mvc:interceptor>
        <mvc:mapping path="/swager-url" />
        <ref bean="swagerInterceptor" />
    </mvc:interceptor>
</mvc:interceptors>

<bean id="swagerInterceptor" class="com.security.SwagerInterceptor">
    <property name="userService" ref="userService" />
</bean>

The interceptor class can be written similar to this:

public class SwagerInterceptor extends HandlerInterceptorAdapter {

       @Override
public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler) throws Exception {
     //Take out user information from the request and validate
 }
Mehul Gayate
  • 344
  • 3
  • 7
  • I am doing that currently but i don't like this approach. – user9735824 Dec 27 '19 at 16:36
  • Okay. I see it as a good solution as you have control. Also, there can't be an automated way in swagger to allow a few users and disallow few because of how Swagger will know type of users you want to allow. Thanks. – Mehul Gayate Dec 27 '19 at 16:43