【问题标题】:spring ldap template authenticationspring ldap模板认证
【发布时间】:2018-11-02 05:38:59
【问题描述】:

我正在尝试通过 spring ldap 对用户进行身份验证。以下是初始化ldap模板的代码。

contextSource = new LdapContextSource();
contextSource.setUrl("ldaps://ldap.example.com");
contextSource.setBase("DC=example,DC=com");
contextSource.setUserDn("backend-app");
contextSource.setPassword("password");
contextSource.afterPropertiesSet();

PoolingContextSource pooledContextSource = new PoolingContextSource(); 
pooledContextSource.setDirContextValidator(new 
DefaultDirContextValidator());
pooledContextSource.setContextSource(contextSource);

ldapTemplate =  new LdapTemplate(pooledContextSource); 
ldapTemplate.afterPropertiesSet();

当我尝试使用 ldapTemplate 验证方法时,它返回 false。

// below line fails
ldapTemplate.authenticate("OU=Service Accounts,OU=Pseudo-Users", "frontend-web", "password");

但是当我使用目录上下文时它可以工作

DirContext ctx = null;
try {
  ctx = contextSource.getContext("frontend-web", "password");
  return true;
} catch (Exception e) {
  logger.error("Login failed", e);
  return false;
} finally {
  LdapUtils.closeContext(ctx);  
}

问题 1: 有没有办法让 ldaptemplate 验证方法起作用?

问题2:为什么直接使用DirectoryContext时不用提供baseDn。 ldap 如何知道在哪里可以找到用户“frontend-web”。它是否在整个目录中搜索用户“frontend-web”

谁能帮忙。

【问题讨论】:

    标签: java ldap jndi spring-ldap


    【解决方案1】:

    问题 1 - 我遇到了完全相同的问题....仍然没有弄清楚如何使用我现有的 LDAP 模板。我将 ldap 配置直接注入到我的服务中,并创建了一个未合并的新“私有”ldapTemplate,如下所示:

    public class AuthController {
    
        private final LdapTemplate ldapTemplate;
    
        AuthController(MyLdapConfig config) {
            LdapContextSource contextSource = new LdapContextSource();
            contextSource.setUrl(config.getUrl());
            contextSource.setUserDn(config.getUserDn());
            contextSource.setPassword(config.getPassword());
            contextSource.afterPropertiesSet();
    
            ldapTemplate = new LdapTemplate(contextSource);
            ldapTemplate.setIgnorePartialResultException(true);
        }
    
        @PostMapping
        public ResponseEntity authenticate(@RequestBody AuthenticationRequest authenticationRequest) {
            if (authenticateUser(authenticationRequest.getUsername(), authenticationRequest.getPassword())) {
                return ResponseEntity.ok().build();
            }
            log.warn("authentication failed for {}", authenticationRequest.getUsername());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    
        // authenticateUser method omitted
    }
    

    问题 2 - 是的

    搜索总是从树根(空路径)开始

    https://docs.spring.io/spring-ldap/docs/2.3.1.RELEASE/reference/#basic-authentication

    【讨论】:

    • 更新 - 我刚刚创建了一个新的@Bean,它是我的“AuthTemplate”,并像我创建我的 ldapTemplate 一样创建它,减去池。然后我构造函数将 AuthTemplate bean 注入到我的服务中.....使测试更容易
    猜你喜欢
    • 2013-01-26
    • 2016-08-11
    • 2012-10-15
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    相关资源
    最近更新 更多