前言

想要在swagger中使用token的一个解决办法  
/**
 * swagger 配置文件 通过schema 和 Contexts 实现token传递
 * @ConditionalOnProperty 配置中设置 swagger 开关
 *
 * @author Salexal.fww
 * @date 2020-03-02 19:42
 */
@Configuration
@EnableSwagger2
@ConditionalOnProperty(prefix = "swaggerConfig", name = "swagger-ui-open", havingValue = "true")
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .securityContexts(securityContexts())
                .securitySchemes(securitySchemes());
    }

    private List<SecurityScheme> securitySchemes() {
        List<SecurityScheme> list = new ArrayList<>();
        // name 为参数名  keyName 是页面传值显示的 keyName, name在swagger鉴权中使用
        list.add(new ApiKey("x-auth-token", "x-auth-token", "header"));
        return list;
    }

    private List<SecurityContext> securityContexts() {
        List<SecurityReference> securityReferences = Collections
                .singletonList(new SecurityReference("x-auth-token"
                        , new AuthorizationScope[]{new AuthorizationScope("global", "accessEverything")}));
        return Collections.singletonList(SecurityContext.builder()
                .securityReferences(securityReferences)
                .forPaths(PathSelectors.none())
                .build());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //title
                .title("数据平台开放接口")
                // description
                .description("Rest API接口")
                //条款地址
                .termsOfServiceUrl("https://mewmewl.cn")
                .version("1.0")
                .build();
    }
// 通过@Authorization(value = "x-auth-token") 来实现token传递
@RestController
@RequestMapping(value = "/auth")
public class AuthController {

    @GetMapping(value = "/hello")
    @ApiOperation(value = "auth", authorizations = {@Authorization(value = "x-auth-token")})
    public String message(String username) {
        return username + " auth success!";
    }
}

效果图如下

swagger