如何配置swaggerconfig或websecurityconfig(spring security)以允许使用swagger ui上的“授权按钮”进行基本授权?

xyhw6mcr  于 2021-10-10  发布在  Java
关注(0)|答案(0)|浏览(179)

我有一个带有RESTAPI的SpringBoot应用程序(springfox 3.0.0),我必须在swagger ui上配置“授权按钮”(basic auth),以便只有具有特定登录名和密码的用户才能访问端点。因此,我需要启用基本身份验证,以便用户只能在使用swagger ui上的“授权”按钮进行身份验证后运行端点。我尝试用以下方式配置WebSecurity配置中的按钮:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
            .withUser("user")
            .password("password")
            .roles("USER");
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            .httpBasic()
            .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().authorizeRequests()
            .antMatchers("/swagger-ui/**", "/v2/api-docs", "/swagger-resources/**",
               "/configuration/security", "/swagger-ui.html", "/webjars/**",
                "/csrf", "/", "/api/settings").permitAll()
            .anyRequest().authenticated()

这是我的招摇过市:

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("example"))
            .paths(PathSelectors.ant("/example/**"))
            .build()
            .apiInfo(apiInfo())
            .securitySchemes(Collections.singletonList(securityScheme()));
}

private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title("Some title")
            .version("Some version")
            .build();
}

private SecurityScheme securityScheme() {
    return new BasicAuth("basicAuth");
}

但是,当我单击Swigger ui上的“授权”按钮并输入任何凭据时,我仍然可以查看和访问API,而且我也被“授权”。我已经尝试过这个解决方案-https://github.com/springfox/springfox/issues/2908 不幸的是,它对我不起作用。那么,有没有人遇到过这个问题?在如何配置上述按钮方面有没有解决办法?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题