【问题标题】:disable swagger-ui based on roles根据角色禁用 swagger-ui
【发布时间】:2019-12-27 16:07:41
【问题描述】:

我知道swagger-ui 可以在spring-boot 应用程序上使用@Profile 完全禁用,但我仍然希望某些特权用户能够访问swagger-ui 而不是完全禁用。

有没有办法做到这一点。

更新:

目前我正在使用interceptor 方法,但我不想要这种方法。

    @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);
}

【问题讨论】:

  • 你在使用 Springfox for Swagger 吗?
  • 是的,我正在使用 springfox 来招摇。

标签: java spring spring-boot swagger-ui


【解决方案1】:

没有您使用的版本或代码,很难提供帮助。但我会尽力而为。

当您使用 swagger-ui 时,您有一个公开的 URL 来访问您的文档(通常是 /swagger-ui.html)。 您正在使用spring-boot,并且正在谈论用户限制,所以我假设您可以使用spring-boot-starter-security。 使用spring-boot-starter-security,您可以轻松配置要保护的 URL(例如关于用户角色)。

这是一个有效的示例配置:

@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")
}

您可以像使用控制器公开的任何 URL 一样保护 Swagger URL。

更多信息:

我可以提供更多帮助:

  • 安全配置摘录
  • 您使用的 Spring-boot 版本

【讨论】:

    【解决方案2】:

    我建议添加一个拦截器,或者如果有的话,你可以在现有的拦截器中处理它。

    在spring配置文件中:

    <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>
    

    拦截器类可以这样写:

    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
     }
    

    【讨论】:

    • 我目前正在这样做,但我不喜欢这种方法。
    • 好的。我认为这是一个很好的解决方案,因为您可以控制。此外,由于 Swagger 将如何知道您想要允许的用户类型,因此在 swagger 中不能有一种自动化的方式来允许少数用户并禁止少数用户。谢谢。
    猜你喜欢
    • 2017-12-07
    • 2021-04-24
    • 2017-10-16
    • 1970-01-01
    • 2014-06-16
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多