Java Spring LDAP

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
  
import java.util.HashMap;
  
import java.util.Hashtable;
  
import java.util.List;
  
import java.util.Map;

import javax.naming.Context;
  
import javax.naming.directory.DirContext;
  
import javax.naming.directory.InitialDirContext;

import org.springframework.ldap.core.DirContextOperations;
  
import org.springframework.ldap.core.DistinguishedName;
  
import org.springframework.ldap.core.LdapTemplate;
  
import org.springframework.ldap.core.support.AbstractContextMapper;
  
import org.springframework.ldap.core.support.DirContextSource;
  
import org.springframework.ldap.support.LdapUtils;
  
/**
   
* This Service does user authentication with LDAP. It uses Spring to do the authentication
   
*
   
* A good chunk of the LDAP code is copy-paste from:
   
* http://static.springsource.organization/spring-ldap/docs/1.3.x/reference/pdf/spring-ldap-reference.pdf
   
*
   
*/
  
public class LDAPService {

private Map<String, String> ldapPropertiesMap=new HashMap<String, String>();

// LDAP Settings
   
public static final String LDAP_PROVIDER_URL = "ldap.provider.url";
   
public static final String LDAP_SECURITY_AUTHENTICATION = "ldap.security.authentication";
   
public static final String LDAP_SECURITY_PRINCIPAL = "ldap.security.principal";
   
public static final String LDAP_SECURITY_CREDENTIALS = "ldap.security.credentials";
   
public static final String LDAP_ADMIN_OU = "ldap.admin.ou";
   
public static final String LDAP_USER_OU = "ldap.user.ou";
   
public static final String LDAP_USER_FILTER = "ldap.user.filter";

private DirContextSource dirCtxSrc;
   
private String userAuthority;
   
private static final String ldapFactory = "com.sun.jndi.ldap.LdapCtxFactory";

private static final String DEFAULT_USER_FILTER = "uid";

public LDAPService() throws Exception {
   
ldapPropertiesMap.put(LDAP_PROVIDER_URL, "ldap://10.0.1.1:10389/ou=system");
   
ldapPropertiesMap.put(LDAP_SECURITY_AUTHENTICATION, "simple");
   
ldapPropertiesMap.put(LDAP_SECURITY_PRINCIPAL, "uid=admin,ou=system");
   
ldapPropertiesMap.put(LDAP_SECURITY_CREDENTIALS, "secret");
   
ldapPropertiesMap.put(LDAP_ADMIN_OU, "ou=admins,ou=system");
   
ldapPropertiesMap.put(LDAP_USER_OU, "ou=users,ou=system");
   
ldapPropertiesMap.put(LDAP_USER_FILTER, "uid=?");
   
this.init();
   
}

private void init() throws Exception {
   
Hashtable<String, String> env = new Hashtable<String, String>();

env.put(Context.INITIAL_CONTEXT_FACTORY, ldapFactory);
   
env.put(Context.PROVIDER_URL, ldapPropertiesMap.get(LDAP_PROVIDER_URL));
   
env.put(Context.SECURITY_AUTHENTICATION,
   
ldapPropertiesMap.get(LDAP_SECURITY_AUTHENTICATION));
   
env.put(Context.SECURITY_PRINCIPAL,
   
ldapPropertiesMap.get(LDAP_SECURITY_PRINCIPAL));
   
env.put(Context.SECURITY_CREDENTIALS,
   
ldapPropertiesMap.get(LDAP_SECURITY_CREDENTIALS));

dirCtxSrc = new DirContextSource();
   
dirCtxSrc.setBaseEnvironmentProperties(env);
   
dirCtxSrc.setUserDn(ldapPropertiesMap.get(LDAP_SECURITY_PRINCIPAL));
   
dirCtxSrc.setPassword(ldapPropertiesMap.get(LDAP_SECURITY_CREDENTIALS));
   
dirCtxSrc.setUrl(ldapPropertiesMap.get(LDAP_PROVIDER_URL));
   
dirCtxSrc.afterPropertiesSet();
   
}

/**
   
* Return user authority after authentication
   
*
   
* @return
   
*/
   
public String getUserAuthority() {
   
return userAuthority;
   
}

public boolean validateLoginCredentials(String username, String password)
   
throws Exception {
   
boolean result = false;

try {
   
String userDn = getDnForUser(username);
   
result = authenticate(userDn, password);

if (result) {
   
String adminGroup = ldapPropertiesMap.get(LDAP_ADMIN_OU);
   
String userGroup = ldapPropertiesMap.get(LDAP_USER_OU);
   
if (adminGroup != null
   
&& userDn.toLowerCase().endsWith(
   
adminGroup.toLowerCase())) {
   
this.userAuthority = adminGroup;
   
} else if (userGroup != null
   
&& userDn.toLowerCase().endsWith(
   
userGroup.toLowerCase())) {
   
this.userAuthority = userGroup;
   
} else {
   
logger.info(username
   
+ " is a valid user, but is not in the either the UserOU or AdminOU");
   
throw new RuntimeException(
   
"Could not locate Authority for User: '" + username
   
+ "' in LDAP");
   
}
   
}
   
return result;
   
} catch (Exception ex) {
   
logger.error("Exception during ldap authentication for User: '"
   
+ username + "'", ex);
   
throw ex;
   
}
   
}

/**
   
* This will find the distinguished name given a uid
   
*
   
* @param uid
   
* @return
   
*/
   
protected String getDnForUser(String uid) {
   
LdapTemplate ldapTemplate = new LdapTemplate(dirCtxSrc);

// Filter
   
String userFilter = ldapPropertiesMap.get(LDAP_USER_FILTER);
   
if (userFilter != null && !userFilter.isEmpty()) {
   
userFilter = userFilter.replaceAll("\?", uid);
   
} else {
   
userFilter = "(" + DEFAULT_USER_FILTER + "=" + uid + ")";
   
}
   
Logger.debug("LDAP USER Filter:" + userFilter);

// Filter f = new EqualsFilter("uid", uid);
   
List result = ldapTemplate.search(DistinguishedName.EMPTY_PATH,
   
userFilter, new AbstractContextMapper() {
   
protected Object doMapFromContext(DirContextOperations ctx) {
   
return ctx.getNameInNamespace();
   
}
   
});

if (result.size() != 1) {
   
throw new RuntimeException("User-'" + uid
   
+ "' not found in LDAP or not unique");
   
}
   
return (String) result.get(0);
   
}

/**
   
* This try to create a Context using the supplied username and password
   
*
   
* @param userDn
   
* @param password
   
* @return
   
*/
   
protected boolean authenticate(String userDn, String password)
   
throws Exception {
   
DirContext ctx = null;

Hashtable<String, String> env = new Hashtable<String, String>();

String providerUrl = (ldapPropertiesMap.get(LDAP_PROVIDER_URL));
   
String securityAuth = (ldapPropertiesMap
   
.get(LDAP_SECURITY_AUTHENTICATION));

env.put(Context.INITIAL_CONTEXT_FACTORY,
   
"com.sun.jndi.ldap.LdapCtxFactory");
   
env.put(Context.PROVIDER_URL, providerUrl);
   
env.put(Context.SECURITY_AUTHENTICATION, securityAuth);
   
env.put(Context.SECURITY_PRINCIPAL, userDn);
   
env.put(Context.SECURITY_CREDENTIALS, password);

try {
   
ctx = new InitialDirContext(env);
   
return true;
   
} catch (Exception e) {
   
// Context creation failed - authentication did not succeed
   
logger.error("Login failed for userDn-'" + userDn + "'",
   
e);
   
throw e;
   
} finally {
   
// It is imperative that the created DirContext instance is always
   
// closed
   
LdapUtils.closeContext(ctx);
   
}
   
}

public Map<String, String> getLdapPropertiesMap() {
   
return ldapPropertiesMap;
   
}

public void setLdapPropertiesMap(Map<String, String> ldapPropertiesMap) {
   
this.ldapPropertiesMap = ldapPropertiesMap;
   
}
  
}