Spring LDAP - Creation of LdapTemplate in standalone java program - Using Spring LDAP as CDI Resource

前提是你 提交于 2021-02-07 07:22:36

问题


I am trying to construct a LdapTemplate object of using spring data.

 public class LDAPTemplate {

        public static void main(String[] args) {
            LdapContextSource lcs = new LdapContextSource();
            lcs.setUrl("ldap://localhost:389/");
            lcs.setUserDn("cn=Manager, dc=example, dc=com");
            lcs.setPassword("secret1");
            lcs.setDirObjectFactory(DefaultDirObjectFactory.class);
            LdapTemplate ldap = new LdapTemplate(lcs);
            ldap.lookup("cn=aaa");

        }

    }

I wanted to know is that the right way to instantiate ldap template object. Because when I perform a lookup, it throws NPE.

I am trying to use LDAP Spring in CDI context without using spring at all. If you have pointers on that would be nice. Does Spring LDAP is dependent on spring?


回答1:


LdapContextSource is InitializingBean so you need to call afterPropertiesSet...

And the JavaDoc:

When using implementations of this class outside of a Spring Context it is necessary to call afterPropertiesSet() when all properties are set, in order to finish up initialization.




回答2:


Correct Code

public class LDAPTemplate {
    public static void main(String[] args) {
        LdapContextSource lcs = new LdapContextSource();
        lcs.setUrl("ldap://localhost:389/");
        lcs.setUserDn("cn=Manager, dc=example, dc=com");
        lcs.setPassword("secret1");
        lcs.setDirObjectFactory(DefaultDirObjectFactory.class);
        lcs.afterPropertiesSet();
        LdapTemplate ldap = new LdapTemplate(lcs);
        ldap.lookup("cn=aaa");

    }
}



回答3:


Solution: To Use Spring LDAP in CDI conte without using Spring IoC

  1. Create a resource producer for LDAP template.

    public class Resources {
    private LdapTemplate template;
    
    @Produces
    //It is a custom qualifier
    @CustomeLDAPTemplate
    public LdapTemplate getTemplate() {
        LdapContextSource lcs = new LdapContextSource();
        lcs.setUrl("ldap://localhost:389/");
        lcs.setUserDn("cn=Manager, dc=example, dc=com");
        lcs.setPassword("secret1");
        lcs.setDirObjectFactory(DefaultDirObjectFactory.class);
        lcs.afterPropertiesSet();
        template = new LdapTemplate(lcs);
        return template;
    }
    
    public void setTemplate(LdapTemplate template) {
        this.template = template;
     }
    }
    
  2. Create a custom qualifier - To say I want tempate object of LdapTemplate and CustomeLDAPTemplate type

    @Qualifier  
    @Retention(RUNTIME)  
    @Target({TYPE,CONSTRUCTOR, METHOD, FIELD})  
    public @interface CustomeLDAPTemplate {}  
    
  3. Implementation on - I used a JAX-WS class to verify.

    @Path("/users")
    @RequestScoped
    public class UserResource {
    
        @Inject
        @CustomeLDAPTemplate
        private LdapTemplate template;
    
        @POST
        @Consumes(MediaType.APPLICATION_XML)
        public Response createUser(InputStream is){
            User user = readStream(is);
            System.out.println("LDAP Look up " + template.lookup("cn=aaa,ou=Org1, dc=example, dc=com").toString());
            uRepo.save(user);
            return Response.created(URI.create("/users/" + user.getUser_id())).build();
        }   
    }
    



回答4:


 /**
 * contextSource
 * @return 
 */
@Bean
public LdapContextSource contextSource() {
    LdapContextSource contextSource = new LdapContextSource();
    contextSource.setUrl(properties.getProperty("ldap.url"));
    contextSource.setBase(properties.getProperty("ldap.base.dn"));
    contextSource.setUserDn(properties.getProperty("ldap.principal"));
    contextSource.setPassword(properties.getProperty("ldap.password"));
    contextSource.setReferral("ignore");
    return contextSource;
}

/**
 * Create Ldap Templelate Instance
 * @return 
 */
@Bean
public LdapTemplate ldapTemplate() {
    LdapTemplate ldapTemplate = new LdapTemplate();
    try {
        ldapTemplate = new LdapTemplate(contextSource());
    } catch (Exception e) {
        log.error("error while creating LDap Template", e);
    }
    return ldapTemplate;
}

/**
 * this Method check if the username and password are valid
 * then return either true if exists and false if not
 * @param username
 * @param password
 * @return
 */
public Boolean authenticateUser(final String username, final String password) {
    boolean auth = false;
    LdapTemplate ldapTemplate = new LdapTemplate(contextSource());
    try {
        ldapTemplate.setIgnorePartialResultException(true);
        log.info("ldapTemplate-->" + ldapTemplate);

        final AndFilter filter = new AndFilter().and(new EqualsFilter("objectclass", OBJECT_CLASS)).and(new EqualsFilter(NETWORK_USER_ENTITY, username));
        auth = ldapTemplate.authenticate(BASE_DN, filter.encode(), password);
        log.info("is Valid user :" + auth);
    } catch (Exception e) {
        log.error("error while creating LDap Template", e);
    }
    return auth;
}


来源:https://stackoverflow.com/questions/22435932/spring-ldap-creation-of-ldaptemplate-in-standalone-java-program-using-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!