簡體   English   中英

Spring 安全性 - 指定哪個 X509 可以訪問哪個特定端點

[英]Spring Security - Specify which X509 can access which specific endpoint

關於如何使用 Spring 安全性來指定哪個客戶端證書可以訪問哪個特定的預定義端點的小問題,請。

通過預定義端點,我的意思是 web 應用程序具有默認端點(不是我通過 @RestController 定義的端點),例如執行器端點/actuator/health/actuator/prometheus或 Spring 雲配置端點,例如/config/myservice/ @PreAuthorize是不可能的。

我只想指定哪個客戶端證書可以訪問哪個端點,例如:

  • 具有UID=Alice的客戶端證書可以訪問/actuator/health/config/myservice
  • UID=Bob的客戶端證書可以訪問/actuator/prometheus

網上有很多例子, How to extract X509 certificate

但是如何在應用程序中進行配置,即這種證書可以訪問什么的映射呢?

謝謝

@Setu 為您提供了解決問題的基本信息。

請考慮以下代碼改編自您引用的一篇文章中的代碼:

@SpringBootApplication
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class X509AuthenticationServer extends WebSecurityConfigurerAdapter {
  ...

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .authorizeRequests()
        // Define the mapping between the different endpoints
        // and the corresponding user roles
        .antMatchers("/actuator/health").hasRole("ACTUATOR_HEALTH")
        .antMatchers("/actuator/prometheus").hasRole("ACTUATOR_PROMETEUS")
        .antMatchers("/config/myservice").hasRole("CONFIG_MYSERVICE")
        // Please, adjust the fallback as appropriate
        .anyRequest().authenticated()
      .and()
        // Configure X509Configurer (https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/configurers/X509Configurer.html)
        .x509()
          .subjectPrincipalRegex("CN=(.*?)(?:,|$)")
          .userDetailsService(userDetailsService())
    ;
  }

  @Bean
  public UserDetailsService userDetailsService() {
    // Ideally this information will be obtained from a database or some
    // configuration information
    return new UserDetailsService() {

      @Override
      public UserDetails loadUserByUsername(String username) {

        Objects.requireNonNull(username);

        List<GrantedAuthority> authorities = null;
        switch (username) {
          // Match the different X509 certificate CNs. Maybe you can use the
          // X509 certificate subject distinguished name to include the role in
          // some way and obtain it directly with the subjectPrincipalRegex
          case "Alice":
            authorities = AuthorityUtils
              .commaSeparatedStringToAuthorityList("ROLE_ACTUATOR_HEALTH, ROLE_CONFIG_MYSERVICE");
            break;

          case "Bob":
            authorities = AuthorityUtils
              .commaSeparatedStringToAuthorityList("ROLE_ACTUATOR_PROMETHEUS");
            break;

          default:
            throw new UsernameNotFoundException(String.format("User '%s' not found!", username));
        }

        return new User(username, "", authorities);
      }
    };
  }
}

請根據需要調整代碼以滿足您的實際端點和用戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM