代码之家  ›  专栏  ›  技术社区  ›  isADon

Spring Boot&Swigger用户界面。设置JWT令牌

  •  31
  • isADon  · 技术社区  · 6 年前

    我有一个像这样大摇大摆的配置

    @EnableSwagger2
    @Configuration
    public class SwaggerConfig {
        @Bean
        public Docket api() {
            List<SecurityScheme> schemeList = new ArrayList<>();
            schemeList.add(new ApiKey(HttpHeaders.AUTHORIZATION, "JWT", "header"));
            return new Docket(DocumentationType.SWAGGER_2)
                    .produces(Collections.singleton("application/json"))
                    .consumes(Collections.singleton("application/json"))
                    .ignoredParameterTypes(Authentication.class)
                    .securitySchemes(schemeList)
                    .useDefaultResponseMessages(false)
                    .select()
                    .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
                    .paths(PathSelectors.any())
                    .build();
        }
    }
    

    在Swagger UI中,当我点击授权按钮时,我在值字段中输入我的JWT令牌 eyJhbGc..nN84qrBg .现在,我希望通过Swagger UI执行的任何请求都会在标题中包含JWT。然而,事实并非如此。 没有请求包含授权标头。

    我错过了什么?

    5 回复  |  直到 6 年前
        1
  •  81
  •   Community CDub    4 年前

    支持 Authorization: Bearer [JWT_TOKEN] header从2.9.2版开始工作

    添加了以下要构建的依赖项。格拉德尔

    compile("io.springfox:springfox-swagger2:2.9.2") {
        exclude module: 'mapstruct' // necessary in my case to not end up with multiple mapstruct versions
    }
    compile "io.springfox:springfox-bean-validators:2.9.2"
    compile "io.springfox:springfox-swagger-ui:2.9.2"
    

    通过

    @Configuration
    @EnableSwagger2
    @Import(springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration.class)
    public class SwaggerConfiguration {
    
        public static final String AUTHORIZATION_HEADER = "Authorization";
        public static final String DEFAULT_INCLUDE_PATTERN = "/api/.*";
        private final Logger log = LoggerFactory.getLogger(SwaggerConfiguration.class);
    
        @Bean
        public Docket swaggerSpringfoxDocket() {
            log.debug("Starting Swagger");
            Contact contact = new Contact(
                "Matyas Albert-Nagy",
                "https://justrocket.de",
                "matyas@justrocket.de");
    
            List<VendorExtension> vext = new ArrayList<>();
            ApiInfo apiInfo = new ApiInfo(
                "Backend API",
                "This is the best stuff since sliced bread - API",
                "6.6.6",
                "https://justrocket.de",
                contact,
                "MIT",
                "https://justrocket.de",
                vext);
    
            Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)
                .pathMapping("/")
                .apiInfo(ApiInfo.DEFAULT)
                .forCodeGeneration(true)
                .genericModelSubstitutes(ResponseEntity.class)
                .ignoredParameterTypes(Pageable.class)
                .ignoredParameterTypes(java.sql.Date.class)
                .directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
                .directModelSubstitute(java.time.ZonedDateTime.class, Date.class)
                .directModelSubstitute(java.time.LocalDateTime.class, Date.class)
                .securityContexts(Lists.newArrayList(securityContext()))
                .securitySchemes(Lists.newArrayList(apiKey()))
                .useDefaultResponseMessages(false);
    
            docket = docket.select()
                .paths(regex(DEFAULT_INCLUDE_PATTERN))
                .build();
            watch.stop();
            log.debug("Started Swagger in {} ms", watch.getTotalTimeMillis());
            return docket;
        }
    
    
        private ApiKey apiKey() {
            return new ApiKey("JWT", AUTHORIZATION_HEADER, "header");
        }
    
        private SecurityContext securityContext() {
            return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex(DEFAULT_INCLUDE_PATTERN))
                .build();
        }
    
        List<SecurityReference> defaultAuth() {
            AuthorizationScope authorizationScope
                = new AuthorizationScope("global", "accessEverything");
            AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
            authorizationScopes[0] = authorizationScope;
            return Lists.newArrayList(
                new SecurityReference("JWT", authorizationScopes));
        }
    }
    

    通过 http://host:port/<context-root>/swagger-ui.html

    按“授权所有请求”并输入 持票人[JWT_代币]

    Press authorize then enter the Bearer JWT Token

    瞧,你的下一个请求将有JWT头

    enter image description here

        2
  •  11
  •   Arnaud F.    4 年前

    对于swagger 2.9.2版

    1. 创建一个SwaggerConfig类。

      @Bean
      public Docket api() {
          return new Docket(DocumentationType.SWAGGER_2)
                  .select()
                  .apis(RequestHandlerSelectors.any())
                  .paths(PathSelectors.any())
                  .build()
                  .apiInfo(apiInfo())
                  .securitySchemes(Arrays.asList(apiKey()));
      }
      
      private ApiInfo apiInfo() {
          return new ApiInfoBuilder()
                  .title("Sig-Predict REST API Document")
                  .description("work in progress")
                  .termsOfServiceUrl("localhost")
                  .version("1.0")
                  .build();
      }
      
      private ApiKey apiKey() {
          return new ApiKey("jwtToken", "Authorization", "header");
      }
      
      1. 然后,对要将此授权标头发送到的每个API进行注释:

        @ApiOperation(value = "", authorizations = { @Authorization(value="jwtToken") })
        
        3
  •  4
  •   rjdkolb Stefan Isele - prefabware.com    6 年前

    你的代码是正确的。

    有一个 bug 在里面 springfox-swagger-ui / springfox-swagger2 版本2.8.0,看起来也是2.9.2。我怀疑您使用的是受此错误影响的版本。

    我只是降级为 2.7.0 而且效果很好。

        4
  •  0
  •   ArMD    4 年前

    为了快速解决问题,我用一个全局参数配置了我的摘要 授权头 在我大摇大摆的课堂上。

        @Configuration
        @EnableSwagger2
        public class SwaggerConfig {
          private static final Set<String> DEFAULT_PRODUCES_CONSUMES = new HashSet<String>(Arrays.asList("application/json"));
        
          @Bean
          public Docket api() {
            ParameterBuilder parameterBuilder = new ParameterBuilder();
            parameterBuilder.name("Authorization")
                    .modelRef(new ModelRef("string"))
                    .parameterType("header")
                    .description("JWT token")
                    .required(true)
                    .build();
            List<Parameter> parameters = new ArrayList<>();
            parameters.add(parameterBuilder.build());
            return new Docket(DocumentationType.SWAGGER_2).apiInfo(DEFAULT_API_INFO)
                .produces(DEFAULT_PRODUCES_CONSUMES)
                .consumes(DEFAULT_PRODUCES_CONSUMES)
                .select()
                .build()
                // Setting globalOperationParameters ensures that authentication header is applied to all APIs
                .globalOperationParameters(parameters);
          }
        }
    

    写了一篇小帖子 authorization-field-in-swagger-ui 关于这个。

        5
  •  0
  •   Mateusz Owsiański    4 年前

    请尝试下面的方法

     return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any()).paths(PathSelectors.regex("/api/v1/.*"))
                .build().groupName("API")
                .globalOperationParameters(newArrayList(
                        new ParameterBuilder().name(HttpHeaders.AUTHORIZATION).description("Authorization token").required(true)
                                .modelRef(new ModelRef("string")).parameterType("header").required(true).build()))
                .apiInfo(apiInfo());