如何使用Spring Security通过基本身份验证保护swagger-ui

时间:2019-06-19 10:11:57

标签: java spring-boot spring-security swagger-ui

我有一个带有rest api的简单Spring Boot应用程序,我需要使用Spring Security使用基本身份验证来保护swagger-ui.html

我已经尝试在Docket api中设置以下内容:

return new Docket(DocumentationType.SWAGGER_2)
                .securitySchemes(auth)
                .securityContexts(securityContexts)
                .select()
                    .apis(RequestHandlerSelectors.basePackage("com.my.package.directory"))
                    .paths(PathSelectors.any())
                    .build()
                .apiInfo(getApiInfo());

和我的spring安全配置:

 @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http
                .csrf().disable()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }

它甚至不需要身份验证,我在做什么错了?

1 个答案:

答案 0 :(得分:0)

尝试一下

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login-page-url")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user =
            User.withDefaultPasswordEncoder()
                .username("username-here")
                .password("password-here")
                .roles("USER")
                .build();

        return new InMemoryUserDetailsManager(user);
    }
}