我的应用程序中有两个不同的用户。Ldap用户和api用户。Ldap用户具有访问端点的权限,而api用户则具有不同的端点的权限。我已经使用UserDetailsService实现了api用户身份验证,并在我的application.yaml文件中包含了详细信息。我现在面临的问题是,我的api用户也正在访问仅Ldap用户应访问的终结点。我该如何预防。请在下面找到我的代码段
public class ServiceSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("ldapProvider")
private AuthenticationProvider authenticationProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
// security for apiuser
http
.authorizeRequests()
.antMatchers(“/abcd/**).hasRole(“admin”)
.and()
.httpBasic().and().userDetailsService(userDetailsService());
// security for ldap users
http
.csrf().disable()
.authorizeRequests()
.antMatchers(“/ghhgh” + "/**").fullyAuthenticated()
.antMatchers("/login*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().and()
.authenticationProvider(authenticationProvider)
.exceptionHandling();
}
public UserDetailsService userDetailsService() {
UserDetails user = User.withUsername(“api”)
.password(passwordEncoder().encode(“test”))
.roles(“admin”)
return new InMemoryUserDetailsManager(user);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
在 Spring 安全性中,确实有可能注册多个身份验证机制。
但是你不能将特定的身份验证提供程序注册到特定的路由。
Spring 安全性文档说:
ProviderManager
是的最常用的实现AuthenticationManager
。ProviderManager
代表List
的AuthenticationProviders
。每个人AuthenticationProvider
都有机会表明身份验证应该成功,失败,或者表明它无法做出决定并允许下游AuthenticationProvider
做出决定。
因此,在每个请求中,AuthenticationProvider
都将一个接一个地检查注册的s,直到一个成功或全部失败。
要解决你的问题,你需要定义多个自定义权限,并为你分配用户。
然后,你可以使用这些权限保护端点。
例如,你赋予每个ldap用户权限LDAP_USER
和每个api用户权限API_USER
。然后,你可以相应地配置安全性:
注册所有AuthenticationProviders:
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(ldapProvider);
auth.userDetailsService(userDetailsService());
}
并配置端点:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
(...)
.authorizeRequests()
// security for apiuser
.antMatchers(“/abcd/**).hasRole(“API_USER”)
// security for ldap users
.antMatchers(“/ghhgh” + "/**").hasRole("LDAP_USER")
(...)
}
@Amir Schenell,您好,谢谢您的解释。我尝试了相同的方法,但是我仍然可以使用apiuser访问ldap端点
您可以将当前的配置发布到您的问题中,以便查看一下吗?
嗨@Amir Schnell,我错过了为ldap添加权限并对其进行修复的问题。非常感谢