我已经集成了Swagger以使用Spring Boot为Spring REST应用程序生成API文档。效果很好,当我点击以下网址时,我可以看到生成的API文档:http://localhost:8080/test/swagger-ui.html 我的问题是如何限制对API的访问?基于硬编码的用户名和密码的基本身份验证至少应该足以胜任。我用maven添加了“ swagger2”依赖项。
这是pom.xml:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
这是大张旗鼓的配置:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.eeocd.test.ws.resource"))
.build();
}
}
答案 0 :(得分:0)
您可以通过向Docket对象添加securityScheme和securityContext来启用身份验证。
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.eeocd.test.ws.resource"))
.build()
.securitySchemes(newArrayList(basicAuth()))
.securityContexts(newArrayList(securityContext()));
}
private BasicAuth basicAuth() {
BasicAuth ba = new BasicAuth("basic");
return ba;
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(apiPaths())
.build();
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return newArrayList(new SecurityReference("basic", authorizationScopes));
}
private Predicate<String> apiPaths() {
return or(regex("/api/v1.*")
);
}
}