关于如何使用 Spring Security 来指定哪个客户端证书可以访问哪个特定的预定义端点的小问题,请。
通过预定义端点,我的意思是 Web 应用程序具有默认端点(不是我通过 @RestController 定义的那些),例如执行器端点 /actuator/health
, /actuator/prometheus
,或 Spring Cloud Config 端点,例如 /config/myservice/
@PreAuthorize
没有可能.
我只想指定哪个客户端证书可以访问哪个端点,例如:
UID=Alice
的客户端证书可以访问/actuator/health
和 /config/myservice
. UID=Bob
的客户端证书可以访问/actuator/prometheus
网上有很多例子,
How to extract X509 certificate
:但是如何在应用程序中配置它,即哪个证书可以访问什么的这种映射?
谢谢
最佳答案
@Setu 为您提供了解决问题的基本信息。
请考虑以下改编自 one of the articles 中的代码的代码你引用了:
@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);
}
};
}
}
请根据需要调整代码以满足您的实际端点和用户。
关于java - Spring Security - 指定哪个 X509 可以访问哪个特定端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67143499/