我正在使用 Spring 构建 REST API,并且目前正在使用自定义用户详细信息服务和以下配置代码对我的所有请求进行身份验证:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
我也在设置
DaoAuthenticationProvider
使用我的用户详细信息服务并使用它来配置全局安全性。现在,我想提供一个端点(虽然仍然使用 HTTP 基本身份验证进行保护)使用不同的用户详细信息服务来检查是否允许用户访问给定资源。
如何为不同的端点使用两种不同的用户详细信息服务?
最佳答案
您可以做的一件事就是拥有两个 WebSecurityConfigurerAdapter
s:
@EnableWebSecurity
@Order(Ordered.HIGHEST_PRECEDENCE)
class FirstEndpointConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) {
http
.requestMatchers()
.antMatchers("/specialendpoint")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.userDetailsService(/* first of your userDetailsServices */);
}
}
@Configuration
class SecondEndpointConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) {
http // all other requests handled here
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.userDetailsService(/* second of your userDetailsServices */);
}
}
requestMatchers()
存在用于定位 springSecurityFilterChain
s 到特定端点。编辑 :Mahmoud Odeh 提出了一个很好的观点,如果用户群相同,那么您可能不需要多个
UserDetailsService
实例。相反,您可以使用一项更改,通过用户帐户的权限来隔离您的特殊端点:http
.authorizeRequests()
.antMatchers("/specialendpoint").hasAuthority("SPECIAL")
.anyRequest().authenticated()
.and()
.httpBasic();
那么,你的单例UserDetailsService
会查找所有用户。它将包括 SPECIAL
GrantedAuthority
在 UserDetails
对于有权访问 /specialendpoint
的用户的实例.
关于spring - 不同端点的多个用户详细信息服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49450556/