我是Spring Security和ldap的新手。 我试图在ldap上添加自定义身份验证,以便只有本地数据库中提到的特定用户才能登录。到目前为止,我已经能够实现ldap身份验证。这是我到目前为止尝试过的-
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${ldap.urls}")
private String ldapUrl;
@Autowired
private CustomAuthenticationProvider authProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().fullyAuthenticated().and().formLogin().loginPage("/login")
.failureUrl("/login?error").permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication().userSearchBase("ou=people").userSearchFilter("(uid={0})").groupSearchBase("ou=groups")
.groupSearchFilter("(uniqueMember={0})").groupRoleAttribute("ou").rolePrefix("ROLE_").contextSource()
.url(ldapUrl);
}
}
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
final String name = authentication.getName();
final String password = authentication.getCredentials().toString();
if (name.equals("user1")) {
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
final UserDetails principal = new User(name, password, grantedAuths);
final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
return auth;
} else {
return null;
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
在这里,我试图添加一个CustomAuthenticationProvider,它仅检查单个特定的用户名,但我没有使用它。如果我使用此authProvider,如何告诉spring有关我的ldap服务器,userSearchBase等的信息?我应该将它们移到application.properties吗?怎么样?
答案 0 :(得分:0)
您可以使用spring.ldap。*将属性放入application.properties中,并且Spring Boot会在运行时自动创建必要的bean。另外,您可以在任何需要的地方为它们注入LdapProperties对象。
https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html