前面讲过使用Swagger2生成API文档,这里是关于直接在浏览器中展示API,并且可以在线测试API。着重从三个方面来概括一下swagger-ui展现:
- Spring Boot端如何启动swagger, 使后端可以接收/v2/api-docs和/swagger-resources请求,并返回相应的response(swagger.json, {url, name}).
- swagger-ui的前端代码生成
- Spring Boot后端和Vue前端如何处理请求的权限
JHipster通过引入jhipster-framework来启动swagger
<dependency>
<groupId>io.github.jhipster</groupId>
<artifactId>jhipster-framework</artifactId>
</dependency>
在io.github.jhipster.config.apidoc.SwaggerAutoConfiguration类中利用注解@EnableSwagger2启动swagger提供的两个服务,这里要注意,启动swagger设定了两个条件:
第一, profiles中必须包含swagger
第二,必须引入依赖springfox-swagger2, springfox-bean-validators,由于之前生成API文档的项目中是通过测试类生成swagger.json文件,通常会把scope设成test, 这里一定要去掉,否则swagger无法启动。
SwaggerAutoConfiguration类中包含了@Configuration注解,此外在/META-INF/spring.factories文件中配置了spring boot auto configuration
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
io.github.jhipster.config.apidoc.SwaggerAutoConfiguration,\
io.github.jhipster.config.apidoc.SwaggerPluginsAutoConfiguration,\
io.github.jhipster.config.JHipsterProperties,\
io.github.jhipster.security.uaa.UaaAutoConfiguration,\
io.github.jhipster.config.info.JHipsterInfoContributorConfiguration,\
io.github.jhipster.config.metric.JHipsterMetricsEndpointConfiguration,\
io.github.jhipster.config.metric.JHipsterLoggingMetricsExportConfiguration,\
io.github.jhipster.security.ssl.UndertowSSLConfiguration
这样当spring boot启动的时候自动寻找第三方jar包中META-INF/spring.factories文件中的配置,自动加载jar包中相关配置,所以只要引入jhipster-framework, 并且profiles中包含swagger, swagger就可以成功启用,
spring:
profiles:
active: dev
include:
- swagger
检测swagger是否成功启用可以通过设定调试模式,来观察启动时日志是否包含swagger启动信息: Started Swagger in 6 ms
logging:
level:
ROOT: DEBUG
io.github.jhipster: DEBUG
com.mycompany.myapp: DEBUG
org.springframework.web: DEBUG
org.springframework.security: DEBUG
JHipster关于swagger权限控制后端有三个方面:
首先,对于swagger-ui/index.html页面的访问权限设定如下:
@Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.{js,html}")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/test/**");
}
然后是比较巧妙的方式来设定对/v2/api-docs和/swagger-resources的访问,
.authorizeRequests()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/register").permitAll()
.antMatchers("/api/activate").permitAll()
.antMatchers("/api/account/reset-password/init").permitAll()
.antMatchers("/api/account/reset-password/finish").permitAll()
.antMatchers("/api/**").authenticated()
可以看到在安全配置中只对/api/**做了权限控制,这间接意味着可以对/v2/api-docs和/swagger-resources进行访问,而通常我们都是写成:
antMatchers("/**").authenticated()
最后对跨域访问的处理如下:
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/management/**", config);
source.registerCorsConfiguration("/v2/api-docs", config);
Vue前端安全处理是在请求中额外添加token信息
requestInterceptor: function(req) {
var authToken = localStorage.getItem("jhi-authenticationToken")
|| sessionStorage.getItem("jhi-authenticationToken");
if (authToken) {
req.headers['Authorization'] = "Bearer " + authToken;
}
return req;
}
JHipster没有在后端引入关于swagger-ui依赖,而是将swagger-ui代码放置在vue代码中,动态设定index.html中urls信息
var urls = [];
axios.get("/swagger-resources").then(function (response) {
response.data.forEach(function (resource) {
urls.push({"name": resource.name, "url": resource.location});
});
urls.sort(function (a, b) {
var x = a.name.toLowerCase(), y = b.name.toLowerCase();
return x < y ? -1 : x > y ? 1 : 0;
});
// Build a system
var ui = SwaggerUIBundle({
urls: urls,
dom_id: '#swagger-ui',
deepLinking: true,
filter: true,
layout: "StandaloneLayout",
withCredentials: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
requestInterceptor: function(req) {
var authToken = localStorage.getItem("jhi-authenticationToken")
|| sessionStorage.getItem("jhi-authenticationToken");
if (authToken) {
req.headers['Authorization'] = "Bearer " + authToken;
}
return req;
}
});
此文件经过webpack打包生成最终swagger-ui/index.html文件
const CopyWebpackPlugin = require('copy-webpack-plugin');
new CopyWebpackPlugin([
{ from: './node_modules/swagger-ui-dist/*.{js,css,html,png}', to: 'swagger-ui', flatten: true, ignore: ['index.html'] },
{ from: './node_modules/axios/dist/axios.min.js', to: 'swagger-ui' },
{ from: './src/main/webapp/swagger-ui/', to: 'swagger-ui' },
{ from: './src/main/webapp/content/', to: 'content' },
{ from: './src/main/webapp/favicon.ico', to: 'favicon.ico' },
{
from: './src/main/webapp/manifest.webapp',
to: 'manifest.webapp'
},
// jhipster-needle-add-assets-to-webpack - JHipster will add/remove third-party resources in this array
{ from: './src/main/webapp/robots.txt', to: 'robots.txt' }
]),
最后我们会在浏览器中看到API列表:
Good Luck,
Cheers!