【问题标题】:Add basic auth to Swagger UI将基本身份验证添加到 Swagger UI
【发布时间】:2020-06-07 21:24:39
【问题描述】:

我已将 swagger 与用于 api 文档的 SAP Hybris commercewebservices api 扩展集成。

这是 spring-v2-spring.xml 中的条目:

<security:http pattern="/v2//api-docs" security="none"/>
<security:http pattern="/v2/*swagger*/**" security="none"/>

这是 springmvc-v2-servlet.xml 中的条目:

<mvc:resources mapping="**/swagger-ui.html" location="classpath:/META-INF/resources/" />
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />

如何将基本身份验证添加到 swagger UI : /rest/v2/swagger-ui.html ?提前致谢。

【问题讨论】:

    标签: java spring swagger swagger-ui hybris


    【解决方案1】:

    我已经在 kotlin 中进行了如下配置。

    @Configuration
    @EnableSwagger2
    @EnableWebSecurity
    class SecurityConfig : WebSecurityConfigurerAdapter() {
    
        override fun configure(http: HttpSecurity) {
            http.csrf().disable()
                .antMatcher("/swagger-ui.html")
                .authorizeRequests()
                .anyRequest().authenticated()
                .and().httpBasic()
        }
    
        @Autowired
        override public fun configure(auth: AuthenticationManagerBuilder) {
            auth.inMemoryAuthentication()
                .withUser("user")
                .password(passwordEncoder().encode("pass123"))
                .authorities("USER")
        }
    
        @Bean
        public fun passwordEncoder(): PasswordEncoder {
            return BCryptPasswordEncoder()
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果您想在 swagger 启用 API 上启用基本身份验证,请使用以下代码。

      @Configuration
      @EnableSwagger2
      public class SwaggerConfig
      {
      
          private static final String AUTHORIZATION_URL = "/authorizationserver/oauth/token";
          private static final String AUTHORIZATION_SCOPE = "basic";
          private static final String ZAMOK_AUTHORIZATION_NAME = "oauth2_password";
      
          @Resource
          private ConfigurationService configurationService;
      
          @Bean
          public Docket commonApi()
          {
              return createDocket("SFront Common API", "/api/(?!sop|cart|wishlist|savings|checkout).*");
          }
      
          @Bean
          public Docket checkoutApi()
          {
              return createDocket("Checkout API", "/api/checkout.*");
          }
      
          @Bean
          public Docket wishlistApi()
          {
              return createDocket("Wishlist API", "/api/wishlist/.*");
          }
      
          @Bean
          public Docket savingsApi()
          {
              return createDocket("Savings API", "/api/savings/.*");
          }
      
          @Bean
          public Docket cartApi()
          {
              return createDocket("Cart API", "/api/cart/.*");
          }
      
          @Bean
          public UiConfiguration uiConfiguration() {
              return UiConfigurationBuilder.builder() //
                      .deepLinking(true) //
                      .displayOperationId(false) //
                      .defaultModelsExpandDepth(1) //
                      .defaultModelExpandDepth(1) //
                      .defaultModelRendering(ModelRendering.EXAMPLE) //
                      .displayRequestDuration(false) //
                      .docExpansion(DocExpansion.NONE) //
                      .filter(false) //
                      .maxDisplayedTags(null) //
                      .operationsSorter(OperationsSorter.ALPHA) //
                      .showExtensions(false) //
                      .tagsSorter(TagsSorter.ALPHA) //
                      .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS) //
                      .validatorUrl(null) //
                      .build();
          }
      
          private Docket createDocket(String groupName, String... regexs)
          {
              ApiSelectorBuilder docket = new Docket(DocumentationType.SWAGGER_2) //
                      .groupName(groupName) //
                      .select() //
                      .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class));
      
              for (String regexp : regexs)
              {
                  docket.paths(regex(regexp));
              }
      
              return docket.build() //
                      .enable(isSwaggerEnabled()) //
                      .securitySchemes(Collections.singletonList(passwordSecurityScheme())) //
                      .securityContexts(Collections.singletonList(oauthSecurityContext())) //
                      .produces(Sets.newHashSet(APPLICATION_JSON));
          }
      
          private boolean isSwaggerEnabled()
          {
              return configurationService.getConfiguration().getBoolean("swagger.enable", false);
          }
      
          private OAuth passwordSecurityScheme()
          {
              AuthorizationScope authorizationScope = new AuthorizationScope(AUTHORIZATION_SCOPE, StringUtils.EMPTY);
              ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant = new ResourceOwnerPasswordCredentialsGrant(
                      AUTHORIZATION_URL);
      
              return new OAuth(ZAMOK_AUTHORIZATION_NAME, Collections.singletonList(authorizationScope),
                      Collections.singletonList(resourceOwnerPasswordCredentialsGrant));
          }
      
          private SecurityContext oauthSecurityContext()
          {
              // @formatter:off
              return SecurityContext.builder()
                      .securityReferences(oauthSecurityReferences())
                      .forPaths(any())
                      .build();
              // @formatter:on
          }
      
          private List<SecurityReference> oauthSecurityReferences()
          {
              AuthorizationScope[] authorizationScopes = {};
      
              return Collections.singletonList(new SecurityReference(ZAMOK_AUTHORIZATION_NAME, authorizationScopes));
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-08
        • 2017-08-17
        • 1970-01-01
        相关资源
        最近更新 更多