[英]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.