Swagger开启JWT
依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
配置类
package soulboy.emos.wx.config;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
//创建docket对象
Docket docket = new Docket(DocumentationType.SWAGGER_2);
//配置描述信息 将ApiInfo对象传入docker.apiInfo属性
ApiInfoBuilder builder = new ApiInfoBuilder();
builder.title("EMOS在线办公系统");
ApiInfo info = builder.build();
docket.apiInfo(info);
//设置swagger生效的路径
ApiSelectorBuilder selectorBuilder = docket.select();
selectorBuilder.paths(PathSelectors.any()); //所有包下面的所有类
selectorBuilder.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)); //使用ApiOperation的类
docket = selectorBuilder.build();
//swagger支持JWT(令牌在哪里)
ApiKey apiKey = new ApiKey("token", "token", "header");
List<ApiKey> apiKeyList = new ArrayList<>();
apiKeyList.add(apiKey);
docket.securitySchemes(apiKeyList);
//后续系统判定用户提交的令牌是有效的,设置令牌在swagger的作用域
AuthorizationScope scope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] scopes = {scope};
SecurityReference reference = new SecurityReference("token", scopes);
List refList = new ArrayList();
refList.add(reference);
SecurityContext context = SecurityContext.builder().securityReferences(refList).build();
List cxtList = new ArrayList();
cxtList.add(context);
docket.securityContexts(cxtList);
return docket;
}
}
测试类
package soulboy.emos.wx.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import soulboy.emos.wx.common.util.R;
@RestController
@RequestMapping("/test")
@Api("测试Web接口")
public class TestController {
@GetMapping("/hi")
@ApiOperation("最简单的测试方法")
public R hi(){
return R.ok();
}
}
URL
http://localhost:8080/emos-wx-api/swagger-ui.html#/test-controller/hiUsingGET