[英]Spring Security LDAP Authentication should authenticate only one user
我希望我的 rest api 仅限于特定用户(超级用户)。 我正在使用 Spring 安全性,如果我提供超级用户/密码,下面的代码可以正常工作,它只检查密码的正确性。 即使我给了一些带有正确密码的随机用户名,它也会说身份验证成功。 如何验证作为 BasicAuth 的一部分给出的用户名是否与“SuperUser”相同
public class BasicAuthSecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${users-ldap.url}")
private String ldapUrl;
@Value("${users-ldap.username}")
private String userDn;
@Value("${users-ldap.password}")
private String password;
@Override
protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.ldapAuthentication()
.userDnPatterns("uid={0}")
.contextSource().url(ldapUrl)
.managerDn(userDn)
.managerPassword(getDrawPassword(password)).and()
.userSearchFilter("sAMAccountName=SuperUser");
}
@RequestMapping
public Authentication getAuth() {
return SecurityContextHolder.getContext().getAuthentication();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.antMatcher("/ws")
.httpBasic().and()
.authorizeRequests()
.anyRequest()
.authenticated().and()
.csrf().disable();
}
}
根据使用自定义身份验证提供的 M.Denum 建议,我可以解决问题
` @Configuration public class LdapAuthenticationProvider 实现 AuthenticationProvider {
@Value("${ldap.url}")
private String ldapUrl;
@Value("${ldap.username}")
private String userDn;
@Value("${ldap.password}")
private String password;
private LdapContextSource contextSource;
private LdapTemplate ldapTemplate;
private void initContext() {
contextSource = new LdapContextSource();
contextSource.setUrl(ldapUrl);
contextSource.setUserDn(userDn);
contextSource.setPassword(password);
contextSource.afterPropertiesSet();
ldapTemplate = new LdapTemplate(contextSource);
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
initContext();
Filter filter = new EqualsFilter("sAMAccountName", authentication.getName());
Boolean authenticate = ldapTemplate.authenticate(LdapUtils.emptyLdapName(), filter.encode(),
authentication.getCredentials().toString());
if (authenticate && (authentication.getName().equalsIgnoreCase(Constants.SERVICE_ACCOUNT)
|| authentication.getName().equalsIgnoreCase(Constants.SERVICE_ACCOUNT_D))) {
UserDetails userDetails = new User(authentication.getName(), authentication.getCredentials().toString(),
new ArrayList<>());
Authentication auth = new UsernamePasswordAuthenticationToken(userDetails,
authentication.getCredentials().toString(), new ArrayList<>());
return auth;
} else {
return null;
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
} `
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.