You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swagger UI访问权限保护:如何通过认证管控Swagger UI访问

解决方案:Dropwizard v2 为 Swagger UI 添加 Basic 认证保护

1. 添加必要依赖

确保项目依赖中包含Dropwizard安全组件和适配v2版本的Swagger Bundle:

<!-- Dropwizard 认证组件 -->
<dependency>
    <groupId>io.dropwizard</groupId>
    <artifactId>dropwizard-auth</artifactId>
    <version>2.1.9</version> <!-- 与你的Dropwizard版本保持一致 -->
</dependency>
<!-- 适配Dropwizard v2的Swagger Bundle -->
<dependency>
    <groupId>io.federecio</groupId>
    <artifactId>dropwizard-swagger</artifactId>
    <version>2.1.0-1</version>
</dependency>

2. 定义用户主体与认证器

先创建简单的用户实体类:

public class User {
    private final String username;

    public User(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }
}

再实现内存版的认证器(生产环境建议替换为数据库/LDAP存储):

import io.dropwizard.auth.AuthenticationException;
import io.dropwizard.auth.Authenticator;
import io.dropwizard.auth.basic.BasicCredentials;
import java.util.Map;
import java.util.Optional;

public class SimpleAuthenticator implements Authenticator<BasicCredentials, User> {
    // 示例用户,生产环境需从安全存储读取
    private static final Map<String, String> VALID_USERS = Map.of(
        "admin", "admin@123",
        "dev", "dev@456"
    );

    @Override
    public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException {
        if (VALID_USERS.containsKey(credentials.getUsername()) &&
            VALID_USERS.get(credentials.getUsername()).equals(credentials.getPassword())) {
            return Optional.of(new User(credentials.getUsername()));
        }
        return Optional.empty();
    }
}

3. 在Application类中注册认证逻辑

修改你的应用启动类,注册Basic认证过滤器:

import io.dropwizard.Application;
import io.dropwizard.auth.AuthDynamicFeature;
import io.dropwizard.auth.AuthValueFactoryProvider;
import io.dropwizard.auth.basic.BasicCredentialAuthFilter;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import io.federecio.dropwizard.swagger.SwaggerBundle;
import io.federecio.dropwizard.swagger.SwaggerBundleConfiguration;
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;

public class YourApp extends Application<YourAppConfig> {

    public static void main(String[] args) throws Exception {
        new YourApp().run(args);
    }

    @Override
    public void initialize(Bootstrap<YourAppConfig> bootstrap) {
        // 注册Swagger Bundle
        bootstrap.addBundle(new SwaggerBundle<>() {
            @Override
            protected SwaggerBundleConfiguration getSwaggerBundleConfiguration(YourAppConfig config) {
                return config.getSwaggerBundleConfiguration();
            }
        });
    }

    @Override
    public void run(YourAppConfig config, Environment environment) {
        // 注册Basic认证过滤器
        environment.jersey().register(new AuthDynamicFeature(
            new BasicCredentialAuthFilter.Builder<User>()
                .setAuthenticator(new SimpleAuthenticator())
                .setRealm("Swagger Protected Zone")
                .buildAuthFilter()
        ));
        environment.jersey().register(RolesAllowedDynamicFeature.class);
        environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));

        // 注册你的业务资源类...
    }
}

4. 配置安全约束保护Swagger路径

在你的Dropwizard配置文件(如config.yml)中,添加安全规则限制Swagger相关路径的访问:

server:
  applicationConnectors:
    - type: http
      port: 8080
  securityConstraints:
    - securityConstraint:
        userConstraint: "*" # 要求必须通过认证才能访问
        uris:
          - "/swagger-ui/*"   # Swagger UI页面路径
          - "/api-docs"       # API文档元数据路径
          - "/api-docs/*"     # 文档细分路径

5. 验证效果

启动应用后访问http://localhost:8080/swagger-ui,浏览器会弹出Basic认证窗口,输入你在SimpleAuthenticator中定义的用户名密码,验证通过后即可进入Swagger UI。

额外说明

  • 若需OAuth2等更复杂的认证方式,只需替换BasicCredentialAuthFilter为对应认证过滤器,核心逻辑仍是通过Dropwizard安全约束保护Swagger路径。
  • 生产环境务必替换内存用户存储为安全的持久化方案,避免硬编码密码。

内容的提问来源于stack exchange,提问作者Amit Joshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:15:27