Debian Codegraph @

src/main/org/h2/security/auth/impl/LdapCredentialsValidator.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: Alessandro Ventura
5 */
6 package org.h2.security.auth.impl;
7
8 import java.util.Hashtable;
9
10 import javax.naming.Context;
11 import javax.naming.directory.DirContext;
12 import javax.naming.directory.InitialDirContext;
13
14 import org.h2.api.CredentialsValidator;
15 import org.h2.security.auth.AuthenticationInfo;
16 import org.h2.security.auth.ConfigProperties;
17
18 /**
19 * Validate credentials by performing an LDAP bind
20 * <p>
21 * Configuration parameters:
22 * </p>
23 * <ul>
24 * <li>bindDnPattern bind dn pattern with %u instead of username
25 * (example: uid=%u,ou=users,dc=example,dc=com)</li>
26 * <li>host ldap server</li>
27 * <li>port of ldap service; optional, by default 389 for insecure, 636 for secure</li>
28 * <li>secure, optional by default is true (use SSL)</li>
29 * </ul>
30 */
31 public class LdapCredentialsValidator implements CredentialsValidator {
32
33 private String bindDnPattern;
34 private String host;
35 private int port;
36 private boolean secure;
37 private String url;
38
39 @Override
40 public void configure(ConfigProperties configProperties) {
41 bindDnPattern = configProperties.getStringValue("bindDnPattern");
42 host = configProperties.getStringValue("host");
43 secure = configProperties.getBooleanValue("secure", true);
44 port = configProperties.getIntValue("port", secure ? 636 : 389);
45 url = "ldap" + (secure ? "s" : "") + "://" + host + ":" + port;
46 }
47
48 @Override
49 public boolean validateCredentials(AuthenticationInfo authenticationInfo) throws Exception {
50 DirContext dirContext = null;
51 try {
52 String dn=bindDnPattern.replace("%u", authenticationInfo.getUserName());
53 Hashtable<String, String> env = new Hashtable<>();
54 env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
55 env.put(Context.PROVIDER_URL, url);
56 env.put(Context.SECURITY_AUTHENTICATION, "simple");
57 env.put(Context.SECURITY_PRINCIPAL, dn);
58 env.put(Context.SECURITY_CREDENTIALS, authenticationInfo.getPassword());
59 if (secure) {
60 env.put(Context.SECURITY_PROTOCOL,"ssl");
61 }
62 dirContext = new InitialDirContext(env);
63 authenticationInfo.setNestedIdentity(dn);
64 return true;
65 } finally {
66 if (dirContext != null) {
67 dirContext.close();
68 }
69 }
70
71 }
72
73 }