0

Подскажите, нет кнопки авторизации в swagger, однако версионность отображается из кода (1.0) введите сюда описание изображения

Моя конфигурация:

@Configuration
public class SwaggerConfig {
    protected static final String AUTH_NAME = "ApiKey";
    protected static final String TITLE = "Uni-file-archive";
    protected static final String DESCRIPTION = "";
    protected static final String VERSION = "1.0";

private Info getInfo() {
    return new Info()
            .title(TITLE)
            .version(VERSION)
            .description(DESCRIPTION);
}

@Bean
public OpenAPI customOpenAPI() {
    return new OpenAPI()
            .components(new Components().addSecuritySchemes(AUTH_NAME, new SecurityScheme()
                    .name(AUTH_NAME)
                    .type(SecurityScheme.Type.OAUTH2)))
            .addSecurityItem(new SecurityRequirement().addList(AUTH_NAME)
            ).info(getInfo());
}
}

Конфигурация секьюрности:

@Slf4j
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private final AppConfig appConfig;

@Override
protected void configure(HttpSecurity http) throws Exception {
    ApiKeyAuthFilter filter = new ApiKeyAuthFilter(appConfig.getHEADER());
    filter.setAuthenticationManager((Authentication authentication) -> {
        String key = (String) authentication.getPrincipal();

        if (!appConfig.getApiKeys().contains(key)) {
            throw new BadCredentialsException("The API key was not found or not the expected value.");
        }

        log.info("Authorized request from " + key.substring(0, key.indexOf("-")));
        authentication.setAuthenticated(true);
        return authentication;
    });

    final String[] SWAGGER_ENDPOINTS = {
        "/swagger-ui/**",
        "/v*/api-docs/**",
        "/swagger-resources/**"
    };

    http
            .authorizeRequests()
            .antMatchers(SWAGGER_ENDPOINTS).permitAll()
            .antMatchers(appConfig.getNoauthEndpoints()).permitAll()
            .and()
            .headers()
            .frameOptions().disable()
            .and()
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().addFilter(filter).authorizeRequests().anyRequest().authenticated();
}
}

Значение ApiKey описана в yaml-конфигурации.

Подскажите, почему не вижу кнопки? Однако если я убираю из swagger конфигурации этот кусок кода, то кнопка появляется, но версионность уже (0.0), т.е. делаю вывод, что конфигурация не из класса SwaggerConfig введите сюда описание изображения

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .components(new Components().addSecuritySchemes(AUTH_NAME, new SecurityScheme()
                        .name(AUTH_NAME)
                        .type(SecurityScheme.Type.OAUTH2)))
                .addSecurityItem(new SecurityRequirement().addList(AUTH_NAME)
                ).info(getInfo());
    }

Далее при запросе, выходит ошибка 403, думаю что ошибка в настройках конфигурации доступа по ApiKey. Подскажите, верна ли моя конфигурация Swagger для ApiKey?

1 ответ 1

0

Проблему решила конфигурацией:

private Info getInfo() {
    return new Info()
            .title(TITLE)
            .version(VERSION)
            .description(DESCRIPTION);
}

@Bean
public OpenAPI customOpenAPI() {
    return new OpenAPI()
            .components(new Components().addSecuritySchemes(AUTH_NAME, new SecurityScheme()
                    .name(AUTH_NAME)
                    .type(SecurityScheme.Type.APIKEY)
                    .in(SecurityScheme.In.HEADER)))
            .addSecurityItem(new SecurityRequirement().addList(AUTH_NAME)
            ).info(getInfo());
}

}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.