美文网首页后台开发Java go php
swagger设置全局token,解决接口需要token验证的问

swagger设置全局token,解决接口需要token验证的问

作者: 爱余星痕 | 来源:发表于2018-04-25 18:46 被阅读1895次

    swagger是一个很牛B的东东,但正常使用时,我们的接口需要登陆才能访问的。即登陆时,要传一个登陆后的token才能访问的。
    那这个怎么设置,才可以让所有接口都允许登陆后访问呢。
    解决办法如下:

    @Configuration
    @EnableWebMvc
    @EnableSwagger2
    public class SwaggerConfig   {
      
        @Bean
        public Docket platformApi() {
    
            return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).forCodeGeneration(true)
                    .select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                    .apis(RequestHandlerSelectors.any())
                    .paths(regex("^.*(?<!error)$"))
                    .build()
                    .securitySchemes(securitySchemes())
                    .securityContexts(securityContexts());
    
    
        }
        private List<ApiKey> securitySchemes() {
            List<ApiKey> apiKeyList= new ArrayList();
            apiKeyList.add(new ApiKey("x-auth-token", "x-auth-token", "header"));
            return apiKeyList;
        }
    
        private List<SecurityContext> securityContexts() {
            List<SecurityContext> securityContexts=new ArrayList<>();
            securityContexts.add(
                    SecurityContext.builder()
                            .securityReferences(defaultAuth())
                            .forPaths(PathSelectors.regex("^(?!auth).*$"))
                            .build());
            return securityContexts;
        }
    
        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;
        }
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder().title("starmark-API").description("©2018 Copyright. Powered By starmark.")
                    // .termsOfServiceUrl("")
                    .contact(new Contact("Starmark", "", "947618@163.com")).license("Apache License Version 2.0")
                    .licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE").version("2.0").build();
        }
    
    }
    

    关键是在securitySchemes()方法配置里增加需要token的配置。
    配置完成后,swagger-ui.html里右上角会有一个Authorize的按钮,录入该token即能成功调用相关接口

    相关文章

      网友评论

      本文标题:swagger设置全局token,解决接口需要token验证的问

      本文链接:https://www.haomeiwen.com/subject/vjgylftx.html