Spring Boot 2 中用于执行器和自定义 API 端点的单独身份验证提供程序



我们有一个 Spring 启动应用程序(Spring 启动版本 2.1.4(,它公开了一个使用 OAuth2 保护的 Rest API。
我们还需要将 Spring Boot 提供的健康检查(执行器(端点公开给仅支持基本身份验证的传统监控工具。
但是,自 Spring Boot 2 以来,执行器与常规应用程序安全规则共享安全配置,因此到目前为止我能看到的唯一选项是使用 Oauth2 保护它或使其不受保护(.permitAll()(。

我尝试使用单独的 WebSecurityConfigurerAdapter(s( 为执行器端点设置 httpBasic 身份验证提供程序,为 API 端点设置 oauth2,使用执行@Order但这两个身份验证提供程序似乎是互斥的。

下面是两个 WebSecurityConfigurerAdapter 实现:

  1. 对于执行器:
@Configuration
@Order(1)
public class ActuatorConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("password")
.roles("ADMIN", "USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//                requestMatchers(EndpointRequest.to(MetricsEndpoint.class))
.antMatchers("/actuator/**")
.hasAnyRole("ADMIN","USER").and().authorizeRequests().and().httpBasic();
}
}
  1. 对于 API:
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Order(10)
public class SecurityConfiguration2 extends WebSecurityConfigurerAdapter {
@Autowired
private CorsFilter corsFilter;
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.cors()
.and()
.addFilterBefore(corsFilter, CsrfFilter.class)
.exceptionHandling()
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
.and()
.headers()
.and()
.authorizeRequests()
.antMatchers("/v2/api-docs").permitAll()
.antMatchers("/authenticate").permitAll()
.antMatchers("/customer/**").hasAuthority("MARKETING")
.anyRequest().authenticated()
.and()
.oauth2Login() // generates the /login page
.successHandler(successHandler())
...
}

任何提示,我如何使这项工作非常受欢迎。

我有相同的用例,这对我有用:

@EnableWebSecurity()
@EnableGlobalMethodSecurity(
securedEnabled = true,
prePostEnabled = true
)
public class WebSecurityConfig {

@Configuration
@Order(3)
public static class ActuatorSecurityAdapter extends WebSecurityConfigurerAdapter {
@Autowired
private AppProperties prop;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatcher(EndpointRequest.toAnyEndpoint())
.authorizeRequests()
.requestMatchers(EndpointRequest.to("info","env")).authenticated()
.requestMatchers(EndpointRequest.to("health")).permitAll()
.anyRequest().hasRole("ADMIN") // Any other endpoint
.and()
.httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
@Override
public UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withUsername(prop.getManagement().getUsername())
.password(prop.getManagement().getPassword()).roles("ACTUATOR").build());
return manager;
}
}

[....]
@Configuration
@Order(1)
public class OAuthSecurityConfig extends WebSecurityConfigurerAdapter {
[...]
}

也许它有助于:)

最新更新