如何使用基本认证

时间:2019-05-08 10:14:08

标签: springfox

我想基于角色向我的swagger ui URI添加基本身份验证。我正在使用springfox 2.9.2,但无法基于角色来限制用户访问任何api。

SecurityConfig.Java

@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
    return super.authenticationManager();
}

@Bean
public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

    @Autowired
    public PasswordEncoder passwordEncoder;

    @Override
    public void configure(HttpSecurity http) throws Exception {

         http
         /*.sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()*/
        .authorizeRequests()
        .antMatchers("/swagger-resources/**", "*.html", "/api/v1/swagger.json")
            .hasRole("ADMIN")
        .anyRequest()
            .authenticated()
        .and().httpBasic()
        .and().anonymous();

    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {


        String passKey1 = passwordEncoder.encode("12345");
        String passKey2 = passwordEncoder.encode("6789");
        auth
            .inMemoryAuthentication()
                .withUser("pqr").password(passKey1).roles("ADMIN").and()
                .withUser("abc").password(passKey2).roles("USER");


    }

}

0 个答案:

没有答案