我的应用程序中有两个不同的用户。Ldap用户和api用户。Ldap用户有权访问端点,api用户访问不同的端点。我使用UserDetailsService实现了api用户身份验证,application.yaml文件中有详细信息。我现在面临的问题是,只有Ldap用户应该访问的端点现在也被访问了我的api用户。我怎么才能阻止这一切。请在下面找到我的代码片段
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();
}
}发布于 2020-12-03 10:38:04
在spring安全性中,确实可以注册多个身份验证机制。
但是,您不能将特定的身份验证提供程序注册到特定的路由。
春天的保安医生说:
ProviderManager是AuthenticationManager最常用的实现。ProviderManager委托给ListofAuthenticationProviders。每个AuthenticationProvider都有机会表明身份验证应该是成功的、失败的,或者表示它不能做出决定并允许下游的AuthenticationProvider作出决定。
因此,在每个请求中,都会逐个检查已注册的AuthenticationProvider,直到其中一个成功,或者全部失败。
要解决问题,您需要定义多个自定义权限,以便为用户分配这些权限。
然后你用这些权限来保护你的端点。
例如,您给每个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")
(...)
}https://stackoverflow.com/questions/65083104
复制相似问题