我正在尝试将基本身份验证添加到Swagger UI,以获得使用Spring Boot构建的Swagger-annotated Jersey 2.0 Web服务 . 我正在使用:
-
Spring Boot 1.5.4
-
spring-boot-starter-jersey
-
Swagger UI 3.0.4
-
(Maven包)swagger-jersey2-jaxrs 1.5.13
我能够在我的资源上使用以下JerseyConfig和Swagger注释生成swagger.json文件 . This article was immensely helpful in getting this far .
@Component
public class JerseyConfiguration extends ResourceConfig {
private static Log logger = LogFactory.getLog(JerseyConfiguration.class);
@Value("${spring.jersey.application-path:/}")
private String apiPath;
public JerseyConfiguration() {
registerEndpoints();
configureSwagger();
}
private void registerEndpoints() {
register(MyEndpoints.class);
// Generate Jersey WADL at /<Jersey's servlet path>/application.wadl
register(WadlResource.class);
// Lets us get to static content like swagger
property(ServletProperties.FILTER_STATIC_CONTENT_REGEX, "((/swagger/.*)|(.*\\.html))");
}
/**
* Configure the Swagger documentation for this API.
*/
private void configureSwagger() {
// Creates file at localhost:port/swagger.json
this.register(ApiListingResource.class);
this.register(SwaggerSerializers.class);
BeanConfig config = new BeanConfig();
config.setConfigId("example-jersey-app");
config.setTitle("Spring Boot + Jersey + Swagger");
config.setVersion("2");
config.setContact("Me <me@example.com>");
config.setSchemes(new String[] {"http", "https"});
config.setResourcePackage("com.example.api");
config.setBasePath(this.apiPath);
config.setPrettyPrint(true);
config.setScan(true);
}
}
现在我希望能够使用基本身份验证从Swagger UI连接到这些服务 . 我在Spring中配置它并可以使用它来验证网站,但不是来自Swagger UI . 不幸的是,没有一个Spring Boot examples currently on the Swagger sample site包含Jersey和身份验证,并且没有一个Jersey示例使用Spring Boot和 @SpringBootApplication
,就像我在我的项目中使用的那样 .
如何让Basic Auth显示在Swagger UI中?
1 回答
通过将
ServletConfigAware
添加到JerseyConfiguration
,我能够使这个工作 . 然后我可以使用Swagger Bootstrap.java examples中使用的相同样式的Swagger配置 .进行这些更改后,将以下注释添加到我的 endpoints :
我看到了以下变化:
添加到我的swagger.json:
此外,在Swagger UI中,一个新的绿色按钮出现在与Schemes下拉列表相同的行中,并在其上显示“Authorize”并打开锁定 . 如果我点击它,弹出窗口会显示我可以输入用户名和密码的位置 . 现在,当我使用Swagger UI“试用”功能时,这些凭据会发送到API .