依赖包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
配置类(securitySchemes与securityContexts作用为配置全局Authorization参数)
@Configuration
@EnableSwagger2
public class SwaggerConfig {
//http://localhost:9007/swagger-ui.html
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("cn.com.dinglisec.iot.uaa.api"))
.paths(PathSelectors.any())
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger构建api文档")
.description("简单优雅的restful风格")
.termsOfServiceUrl("")
.version("1.0")
.build();
}
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeys = new ArrayList<>();
apiKeys.add(new ApiKey("Authorization", "Authorization", "header"));
return apiKeys;
}
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContexts = new ArrayList<>();
securityContexts.add(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$")).build());
return securityContexts;
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences = new ArrayList<>();
securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
return securityReferences;
}
}
配置跳过过滤器 解决swagger2不能获取页面的问题
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private static final PathMatcher pathMatcher = new AntPathMatcher();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (StringUtils.contains(request.getServletPath(), "swagger")
|| StringUtils.contains(request.getServletPath(), "webjars")
|| StringUtils.contains(request.getServletPath(), "v2")) {
if (request.getServerName().equals("localhost")) {
filterChain.doFilter(request, response);
}
} else {
if (isExceededUrl(request)) {
// 登录注册请求直接放行
filterChain.doFilter(request, response);
} else {
// 获取请求头中的Authorization信息
String tokenHeader = request.getHeader(TokenConstants.TOKEN_HEADER);
// token不存在则返回
if (StringUtils.isBlank(tokenHeader) || !tokenHeader.startsWith(TokenConstants.TOKEN_PREFIX)) {
ServletOutputStream out = response.getOutputStream();
out.print(ResponseConstants.TOKEN_IS_INVALID);
out.close();
return;
}
// token过期返回
if (JwtUtil.isExpiration(JwtUtil.getTokenByHeader(tokenHeader))) {
ServletOutputStream out = response.getOutputStream();
out.print(ResponseConstants.TOKEN_IS_INVALID);
out.close();
return;
}
String uid = "";
try {
uid = JwtUtil.getUidByTokenHeader(request.getHeader(TokenConstants.TOKEN_HEADER));
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("uid", uid);
HttpServletRequest req = (HttpServletRequest) request;
MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(req);
mutableRequest.putHeader("uid", uid);
filterChain.doFilter(request, response);
}
}
}
/**
* @Description:我们只对地址 /api 开头的api检查jwt. 不然的话登录/login也需要jwt 做url匹配,参考
* https://www.cnblogs.com/zhangxiaoguang/p/5855113.html
* @param request
* @return boolean
*/
private boolean isProtectedUrl(HttpServletRequest request) {
return pathMatcher.match("/**", request.getServletPath());
}
/**
* @Description:登录注册不做校验
* @param request
* @return boolean
*/
private boolean isExceededUrl(HttpServletRequest request) {
return pathMatcher.match("/user/login", request.getServletPath())
|| pathMatcher.match("/user/register", request.getServletPath());
}
}
PREVIOUSDocket(Swagger2中应用)
NEXTlogback配置