不同端点的多个用户详细信息服务 [英] Multiple user details services for different endpoints
问题描述
我正在使用 Spring 构建 REST API,并且目前正在使用自定义用户详细信息服务和此配置代码对我的所有请求进行身份验证:
I am building a REST API using Spring and am currently authenticating all my requests using a custom user details service and this configuration code:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
我还设置了一个 DaoAuthenticationProvider
来使用我的用户详细信息服务并使用它来配置全局安全性.
I am also setting up a DaoAuthenticationProvider
to use the my user details service and using that to configure global security.
现在,我想提供一个端点(虽然仍然使用 HTTP 基本身份验证进行保护)使用不同的用户详细信息服务来检查是否允许用户访问给定资源.
Now, I want to provide an endpoint that (while still secured with HTTP basic authentication) uses a different user details service to check whether the user is allowed to access the given resource.
如何为不同的端点使用两种不同的用户详细信息服务?
How do I use two different user details services for different endpoints?
推荐答案
你可以做的一件事就是拥有两个 WebSecurityConfigurerAdapter
:
One thing you can do is have two 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 定位到特定端点.
requestMatchers()
exists for targeting springSecurityFilterChain
s to specific endpoints.
编辑:Mahmoud Odeh 提出了一个很好的观点,即如果用户群相同,那么您可能不需要多个 UserDetailsService
实例.相反,您可以使用一项更改,通过对用户帐户的授权来隔离您的特殊端点:
EDIT: Mahmoud Odeh makes a good point that if the user bases are the same, then you may not need multiple UserDetailsService
instances. Instead, you can use one change that isolates your special endpoint by an authority on the user's account:
http
.authorizeRequests()
.antMatchers("/specialendpoint").hasAuthority("SPECIAL")
.anyRequest().authenticated()
.and()
.httpBasic();
然后,您的单个 UserDetailsService
将查找所有用户.对于有权访问 /specialendpoint
的用户,它将在 UserDetails
实例中包含 SPECIAL
GrantedAuthority
.
Then, your single UserDetailsService
would look up all users. It would include the SPECIAL
GrantedAuthority
in the UserDetails
instance for users who have access to /specialendpoint
.
这篇关于不同端点的多个用户详细信息服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!