/
XWikiLDAPAuthServiceImpl.java
782 lines (651 loc) · 30.6 KB
/
XWikiLDAPAuthServiceImpl.java
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.contrib.ldap;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.securityfilter.filter.SecurityRequestWrapper;
import org.securityfilter.realm.SimplePrincipal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.context.Execution;
import org.xwiki.context.ExecutionContext;
import org.xwiki.text.StringUtils;
import com.novell.ldap.LDAPDN;
import com.novell.ldap.LDAPException;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.user.api.XWikiUser;
import com.xpn.xwiki.user.impl.xwiki.XWikiAuthServiceImpl;
import com.xpn.xwiki.web.Utils;
import com.xpn.xwiki.web.XWikiRequest;
/**
* This class provides an authentication method that validates a user trough LDAP against a directory. It gives LDAP
* users access if they belong to a particular group, creates XWiki users if they have never logged in before and
* synchronizes membership to XWiki groups based on membership to LDAP groups.
*
* @version $Id$
* @since 8.3
*/
public class XWikiLDAPAuthServiceImpl extends XWikiAuthServiceImpl
{
/**
* Default unique user field name.
*/
private static final String LDAP_DEFAULT_UID = "cn";
/**
* Logging tool.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(XWikiLDAPAuthServiceImpl.class);
private static final String CONTEXT_CONFIGURATION = "ldap.configuration";
private final ConcurrentMap<String, String> lockMap = new ConcurrentHashMap<>();
private Execution execution;
protected ExecutionContext getExecutionContext()
{
if (this.execution == null) {
this.execution = Utils.getComponent(Execution.class);
}
return this.execution.getContext();
}
/**
* @deprecated since 9.1.1, use {@link #initConfiguration(String)} instead
*/
@Deprecated
protected XWikiLDAPConfig initConfiguration(String authInput, XWikiContext xcontext)
{
return initConfiguration(authInput);
}
/**
* @since 9.1.1
*/
protected XWikiLDAPConfig initConfiguration(String authInput)
{
ExecutionContext econtext = getExecutionContext();
if (econtext != null) {
XWikiLDAPConfig configuration = createXWikiLDAPConfig(authInput);
econtext.setProperty(CONTEXT_CONFIGURATION, configuration);
return configuration;
}
return XWikiLDAPConfig.getInstance();
}
/**
* Allow extenders of this class to override this method and provide their own XWikiLDAPConfig instance (for example
* in order to use a different configuration source).
*
* @since 9.1.1
*/
protected XWikiLDAPConfig createXWikiLDAPConfig(String authInput)
{
return new XWikiLDAPConfig(authInput);
}
protected void removeConfiguration()
{
ExecutionContext econtext = getExecutionContext();
if (econtext != null) {
econtext.removeProperty(CONTEXT_CONFIGURATION);
}
}
protected XWikiLDAPConfig getConfiguration()
{
ExecutionContext econtext = getExecutionContext();
if (econtext != null) {
XWikiLDAPConfig configuration = (XWikiLDAPConfig) econtext.getProperty(CONTEXT_CONFIGURATION);
if (configuration != null) {
return configuration;
}
}
return XWikiLDAPConfig.getInstance();
}
// REMOTE_USER
@Override
public XWikiUser checkAuth(XWikiContext context) throws XWikiException
{
String httpHeader = getConfiguration().getHttpHeader();
XWikiUser user = null;
String remoteUser;
if (StringUtils.isEmpty(httpHeader)) {
remoteUser = context.getRequest().getRemoteUser();
} else {
remoteUser = context.getRequest().getHeader(httpHeader);
}
if (remoteUser != null) {
LOGGER.debug("REMOTE_USER: {}", remoteUser);
user = checkAuthSSO(remoteUser, context);
}
if (user == null) {
user = super.checkAuth(context);
}
LOGGER.debug("XWikiUser: {}", user);
return user;
}
private Principal checkSessionPrincipal(String remoteUser, XWikiRequest request)
{
LOGGER.debug("Try to find principal in the session for remote user [{}]", remoteUser);
// Get the current user
Principal principal =
(Principal) request.getSession().getAttribute(SecurityRequestWrapper.PRINCIPAL_SESSION_KEY);
if (principal != null) {
String storedRemoteUser = (String) request.getSession().getAttribute("ldap.remoteuser");
// If the remote user changed authenticate again
if (remoteUser.equals(storedRemoteUser)) {
return principal;
} else {
LOGGER.debug(" There is a principal in the sessions but it does not match remote user [{}]"
+ " (stored remote user is [{}])", remoteUser, storedRemoteUser);
}
} else {
LOGGER.debug(" There is no principal at all in the session");
}
return null;
}
private XWikiUser checkAuthSSO(String remoteUser, XWikiContext context)
{
XWikiRequest request = context.getRequest();
// Check if the user is already authenticated
Principal principal = checkSessionPrincipal(remoteUser, request);
XWikiUser user;
if (principal == null) {
// Authenticate
principal = checkAuthSSOSync(remoteUser, request, context);
if (principal == null) {
return null;
}
// Remember user in the session
request.getSession().setAttribute(SecurityRequestWrapper.PRINCIPAL_SESSION_KEY, principal);
request.getSession().setAttribute("ldap.remoteuser", remoteUser);
user = new XWikiUser(principal.getName());
} else {
user = new XWikiUser(principal.getName().startsWith(context.getWikiId())
? principal.getName().substring(context.getWikiId().length() + 1) : principal.getName());
}
LOGGER.debug("XWikiUser = [{}]", user);
removeConfiguration();
return user;
}
private Principal checkAuthSSOSync(String remoteUser, XWikiRequest request, XWikiContext context)
{
// TODO: replace with computeIfAbsent when moving to Java 8
String lock = this.lockMap.putIfAbsent(remoteUser, remoteUser);
if (lock == null) {
lock = this.lockMap.get(remoteUser);
}
synchronized (lock) {
// Check if the user was authenticated by another thread in the meantime
Principal principal = checkSessionPrincipal(remoteUser, request);
if (principal == null) {
// Authenticate
principal = ldapAuthenticate(remoteUser, null, true, false, context);
}
return principal;
}
}
// LOGIN/PASS
@Override
public Principal authenticate(String userId, String password, XWikiContext context) throws XWikiException
{
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Starting LDAP authentication");
}
/*
* TODO: Put the next 4 following "if" in common with XWikiAuthService to ensure coherence This method was
* returning null on failure so I preserved that behaviour, while adding the exact error messages to the context
* given as argument. However, the right way to do this would probably be to throw XWikiException-s.
*/
if (userId == null) {
// If we can't find the username field then we are probably on the login screen
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("The provided user is null."
+ " We don't try to authenticate, it probably means the user is in non logged mode.");
}
return null;
}
// Check for empty usernames
if (userId.equals("")) {
context.put("message", "nousername");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("LDAP authentication failed: login empty");
}
return null;
}
// Check for empty passwords
if ((password == null) || (password.trim().equals(""))) {
context.put("message", "nopassword");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("LDAP authentication failed: password null or empty");
}
return null;
}
// Check for superadmin
if (isSuperAdmin(userId)) {
return authenticateSuperAdmin(password, context);
}
// Try authentication against ldap
Principal principal = ldapAuthenticate(userId, password, false, true, context);
if (principal == null) {
// Fallback to local DB only if trylocal is true
principal = xwikiAuthenticate(userId, password, context);
}
if (LOGGER.isDebugEnabled()) {
if (principal != null) {
LOGGER.debug("LDAP authentication succeed with principal [{}]", principal.getName());
} else {
LOGGER.debug("LDAP authentication failed for user [{}]", userId);
}
}
removeConfiguration();
return principal;
}
/**
* @param name the name to convert.
* @return a valid XWiki user name:
* <ul>
* <li>Remove '.'</li>
* </ul>
* @deprecated since 9.0, use {@link XWikiLDAPUtils#cleanXWikiUserPageName(String)} instead
*/
@Deprecated
protected String getValidXWikiUserName(String name)
{
return XWikiLDAPUtils.cleanXWikiUserPageName(name);
}
/**
* Try both local and global ldap login and return {@link Principal}.
*
* @param userId the id of the user provided in input
* @param password the password of the user to log in.
* @param context the XWiki context.
* @return the {@link Principal}.
*/
protected Principal ldapAuthenticate(String userId, String password, XWikiContext context)
{
Principal principal = ldapAuthenticate(userId, password, false, true, context);
removeConfiguration();
return principal;
}
/**
* Try both local and global ldap login and return {@link Principal}.
*
* @param userId the id of the user provided in input
* @param password the password of the user to log in.
* @param trusted is it a trusted authentication (should the credentials be validated)
* @param compactPrincipal if true the user principal should not contain the wiki in case of local authentication
* @param context the XWiki context.
* @return the {@link Principal}.
*/
private Principal ldapAuthenticate(String userId, String password, boolean trusted, boolean compactPrincipal,
XWikiContext context)
{
Principal principal = null;
// First we check in the local context for a valid ldap user
try {
principal = ldapAuthenticateInContext(userId, null, password, trusted, context, compactPrincipal);
} catch (Exception e) {
// continue
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Local LDAP authentication failed.", e);
}
}
// If local ldap failed, try global ldap
if (principal == null && !context.isMainWiki()) {
// Then we check in the main database
String db = context.getWikiId();
try {
context.setWikiId(context.getMainXWiki());
try {
principal = ldapAuthenticateInContext(userId, null, password, trusted, context, false);
} catch (Exception e) {
// continue
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Global LDAP authentication failed.", e);
}
}
} finally {
context.setWikiId(db);
}
}
return principal;
}
/**
* Try both local and global DB login if trylocal is true {@link Principal}.
*
* @param userId the id of the user provided in input
* @param ldapPassword the password of the user to log in.
* @param context the XWiki context.
* @return the {@link Principal}.
* @throws XWikiException error when checking user name and password.
*/
protected Principal xwikiAuthenticate(String userId, String ldapPassword, XWikiContext context)
throws XWikiException
{
Principal principal = null;
String trylocal = getConfiguration().getLDAPParam("ldap_trylocal", "0");
if ("1".equals(trylocal)) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Trying authentication against XWiki DB");
}
principal = super.authenticate(userId, ldapPassword, context);
}
return principal;
}
/**
* Try LDAP login for given context and return {@link Principal}.
*
* @param userId the id of the user provided in input
* @param validXWikiUserName the name of the XWiki user to log in.
* @param password the password of the user to log in.
* @param context the XWiki context.
* @return the {@link Principal}.
* @throws XWikiException error when login.
* @throws UnsupportedEncodingException error when login.
* @throws LDAPException error when login.
*/
protected Principal ldapAuthenticateInContext(String userId, String validXWikiUserName, String password,
XWikiContext context) throws XWikiException, UnsupportedEncodingException, LDAPException
{
return ldapAuthenticateInContext(userId, validXWikiUserName, password, context, false);
}
/**
* Try LDAP login for given context and return {@link Principal}.
*
* @param userId the id of the user provided in input
* @param password the password of the user to log in.
* @param context the XWiki context.
* @return the {@link Principal}.
* @throws XWikiException error when login.
* @throws UnsupportedEncodingException error when login.
* @throws LDAPException error when login.
*/
protected Principal ldapAuthenticateInContext(String userId, String password, XWikiContext context)
throws XWikiException, UnsupportedEncodingException, LDAPException
{
return ldapAuthenticateInContext(userId, password, context, false);
}
/**
* Try LDAP login for given context and return {@link Principal}.
*
* @param userId the id of the user provided in input
* @param password the password of the user to log in.
* @param context the XWiki context.
* @param local indicate if it's a local authentication. Supposed to return a local user {@link Principal} (without
* the wiki name).
* @return the {@link Principal}.
* @throws XWikiException error when login.
* @throws UnsupportedEncodingException error when login.
* @throws LDAPException error when login.
*/
protected Principal ldapAuthenticateInContext(String userId, String password, XWikiContext context, boolean local)
throws XWikiException, UnsupportedEncodingException, LDAPException
{
return ldapAuthenticateInContext(userId, null, password, context, local);
}
/**
* Try LDAP login for given context and return {@link Principal}.
*
* @param userId the id of the user provided in input
* @param validXWikiUserName the name of the XWiki user to log in.
* @param password the password of the user to log in.
* @param context the XWiki context.
* @param local indicate if it's a local authentication. Supposed to return a local user {@link Principal} (without
* the wiki name).
* @return the {@link Principal}.
* @throws XWikiException error when login.
* @throws UnsupportedEncodingException error when login.
* @throws LDAPException error when login.
*/
protected Principal ldapAuthenticateInContext(String userId, String validXWikiUserName, String password,
XWikiContext context, boolean local) throws XWikiException, UnsupportedEncodingException, LDAPException
{
return ldapAuthenticateInContext(userId, validXWikiUserName, password, false, context, local);
}
/**
* Try LDAP login for given context and return {@link Principal}.
*
* @param authInput the id of the user provided in input
* @param validXWikiUserName the name of the XWiki user to log in.
* @param password the password of the user to log in.
* @param trusted true in case of trusted authentication (i.e. should the credentials be validated or not)
* @param context the XWiki context.
* @param local indicate if it's a local authentication. Supposed to return a local user {@link Principal} (without
* the wiki name).
* @return the {@link Principal}.
* @throws XWikiException error when login.
* @throws UnsupportedEncodingException error when login.
* @throws LDAPException error when login.
* @since 9.0
*/
protected Principal ldapAuthenticateInContext(String authInput, String validXWikiUserName, String password,
boolean trusted, XWikiContext context, boolean local)
throws XWikiException, UnsupportedEncodingException, LDAPException
{
Principal principal = null;
String trimedAuthInput = authInput.trim();
XWikiLDAPConfig configuration = initConfiguration(trimedAuthInput);
XWikiLDAPConnection connector = new XWikiLDAPConnection(configuration);
XWikiLDAPUtils ldapUtils = new XWikiLDAPUtils(connector, configuration);
ldapUtils.setUidAttributeName(configuration.getLDAPParam(XWikiLDAPConfig.PREF_LDAP_UID, LDAP_DEFAULT_UID));
ldapUtils.setGroupClasses(configuration.getGroupClasses());
ldapUtils.setGroupMemberFields(configuration.getGroupMemberFields());
ldapUtils.setBaseDN(configuration.getLDAPParam("ldap_base_DN", ""));
ldapUtils.setUserSearchFormatString(configuration.getLDAPParam("ldap_user_search_fmt", "({0}={1})"));
ldapUtils.setResolveSubgroups(configuration.getLDAPParamAsLong("ldap_group_sync_resolve_subgroups", 1) == 1);
String uid = configuration.getMemoryConfiguration().get("uid");
// ////////////////////////////////////////////////////////////////////
// 1. check if ldap authentication is off => authenticate against db
// ////////////////////////////////////////////////////////////////////
if (!configuration.isLDAPEnabled()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("LDAP authentication failed: LDAP not activ");
}
return principal;
}
// ////////////////////////////////////////////////////////////////////
// 2. bind to LDAP => if failed try db
// ////////////////////////////////////////////////////////////////////
if (!connector.open(trimedAuthInput, password, context)) {
throw new XWikiException(XWikiException.MODULE_XWIKI_USER, XWikiException.ERROR_XWIKI_USER_INIT,
"Bind to LDAP server failed.");
}
try {
// ////////////////////////////////////////////////////////////////////
// 3. find XWiki user profile page
// ////////////////////////////////////////////////////////////////////
XWikiDocument userProfile = ldapUtils.getUserProfileByUid(validXWikiUserName, trimedAuthInput, context);
if (userProfile == null) {
// Try to search just the UID (in case this user was created before a move to multidomain)
if (!trimedAuthInput.equals(uid) && getConfiguration().getTestLoginFor().contains(trimedAuthInput)) {
userProfile = ldapUtils.getUserProfileByUid(validXWikiUserName, uid, context);
}
}
// ////////////////////////////////////////////////////////////////////
// 4. check if bind DN is user DN
// ////////////////////////////////////////////////////////////////////
String ldapDn = null;
String bindDNFormat = configuration.getLDAPBindDN();
String bindDN = configuration.getLDAPBindDN(trimedAuthInput, password);
// Active directory support a special non DN form for bind but does not accept it at search level
if (!bindDNFormat.equals(bindDN) && LDAPDN.isValid(bindDN)) {
ldapDn = bindDN;
}
// ////////////////////////////////////////////////////////////////////
// 5. if group param, verify group membership (& get DN)
// ////////////////////////////////////////////////////////////////////
String filterGroupDN = configuration.getLDAPParam("ldap_user_group", "");
if (filterGroupDN.length() > 0) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Checking if the user belongs to the user group: {}", filterGroupDN);
}
ldapDn = ldapUtils.isInGroup(uid, ldapDn, filterGroupDN, context);
if (ldapDn == null) {
throw new XWikiException(XWikiException.MODULE_XWIKI_USER, XWikiException.ERROR_XWIKI_USER_INIT,
"LDAP user {0} does not belong to LDAP group {1}.", null, new Object[] {uid, filterGroupDN});
}
}
// ////////////////////////////////////////////////////////////////////
// 6. if exclude group param, verify group membership
// ////////////////////////////////////////////////////////////////////
String excludeGroupDN = configuration.getLDAPParam("ldap_exclude_group", "");
if (excludeGroupDN.length() > 0) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Checking if the user does not belongs to the exclude group: {}", excludeGroupDN);
}
if (ldapUtils.isInGroup(uid, ldapDn, excludeGroupDN, context) != null) {
throw new XWikiException(XWikiException.MODULE_XWIKI_USER, XWikiException.ERROR_XWIKI_USER_INIT,
"LDAP user {0} should not belong to LDAP group {1}.", null, new Object[] {uid, filterGroupDN});
}
}
// ////////////////////////////////////////////////////////////////////
// 7. if no dn search for user
// ////////////////////////////////////////////////////////////////////
List<XWikiLDAPSearchAttribute> searchAttributes = null;
// if we still don't have a dn, search for it. Also get the attributes, we might need
// them
if (ldapDn == null) {
searchAttributes = ldapUtils.searchUserAttributesByUid(uid, ldapUtils.getAttributeNameTable(context));
if (searchAttributes != null) {
for (XWikiLDAPSearchAttribute searchAttribute : searchAttributes) {
if ("dn".equals(searchAttribute.name)) {
ldapDn = searchAttribute.value;
break;
}
}
}
}
if (ldapDn == null) {
throw new XWikiException(XWikiException.MODULE_XWIKI_USER, XWikiException.ERROR_XWIKI_USER_INIT,
"Can't find LDAP user DN for input [" + trimedAuthInput + "]");
}
// ////////////////////////////////////////////////////////////////////
// 8. apply validate_password property or if user used for LDAP connection is not the one
// authenticated try to bind
// ////////////////////////////////////////////////////////////////////
if (!trusted) {
if ("1".equals(configuration.getLDAPParam("ldap_validate_password", "0"))) {
String passwordField = configuration.getLDAPParam("ldap_password_field", "userPassword");
if (!connector.checkPassword(ldapDn, password, passwordField)) {
LOGGER.debug("Password comparison failed, are you really sure you need validate_password ?"
+ " If you don't enable it, it does not mean user credentials are not validated."
+ " The goal of this property is to bypass standard LDAP bind"
+ " which is usually bad unless you really know what you do.");
throw new XWikiException(XWikiException.MODULE_XWIKI_USER, XWikiException.ERROR_XWIKI_USER_INIT,
"LDAP authentication failed:" + " could not validate the password: wrong password for "
+ ldapDn);
}
} else if (!ldapDn.equals(bindDN)) {
// Validate user credentials
connector.bind(ldapDn, password);
// Rebind admin user
connector.bind(bindDN, configuration.getLDAPBindPassword(trimedAuthInput, password));
}
}
// ////////////////////////////////////////////////////////////////////
// 9. if not already found, search for XWiki user profile page by dn
// ////////////////////////////////////////////////////////////////////
boolean isNewUser = userProfile == null || userProfile.isNew();
if (isNewUser) {
userProfile = ldapUtils.getUserProfileByDn(validXWikiUserName, ldapDn, context);
isNewUser = userProfile == null || userProfile.isNew();
}
// ////////////////////////////////////////////////////////////////////
// 10. sync user
// ////////////////////////////////////////////////////////////////////
userProfile = syncUser(userProfile, searchAttributes, ldapDn, trimedAuthInput, ldapUtils, context);
// from now on we can enter the application
if (local) {
principal = new SimplePrincipal(userProfile.getFullName());
} else {
principal = new SimplePrincipal(userProfile.getPrefixedFullName());
}
// ////////////////////////////////////////////////////////////////////
// 10. sync groups membership
// ////////////////////////////////////////////////////////////////////
try {
syncGroupsMembership(userProfile.getFullName(), ldapDn, isNewUser, ldapUtils, context);
} catch (XWikiException e) {
LOGGER.error("Failed to synchronise user's groups membership", e);
}
} finally {
connector.close();
}
return principal;
}
/**
* Update or create XWiki user base on LDAP.
*
* @param userProfile the XWiki user profile page.
* @param searchAttributeListIn the attributes.
* @param ldapDn the LDAP user DN.
* @param authInput the input used to identify the user
* @param ldapUtils the LDAP communication tool.
* @param context the XWiki context.
* @return the XWiki user document
* @throws XWikiException error when updating or creating XWiki user.
*/
protected XWikiDocument syncUser(XWikiDocument userProfile, List<XWikiLDAPSearchAttribute> searchAttributeListIn,
String ldapDn, String authInput, XWikiLDAPUtils ldapUtils, XWikiContext context) throws XWikiException
{
return ldapUtils.syncUser(userProfile, searchAttributeListIn, ldapDn, authInput, context);
}
/**
* Synchronize user XWiki membership with it's LDAP membership.
*
* @param xwikiUserName the name of the user.
* @param ldapDn the LDAP DN of the user.
* @param createuser indicate if the user is created or updated.
* @param ldapUtils the LDAP communication tool.
* @param context the XWiki context.
* @throws XWikiException error when synchronizing user membership.
*/
protected void syncGroupsMembership(String xwikiUserName, String ldapDn, boolean createuser,
XWikiLDAPUtils ldapUtils, XWikiContext context) throws XWikiException
{
XWikiLDAPConfig configuration = getConfiguration();
// got valid group mappings
Map<String, Set<String>> groupMappings = configuration.getGroupMappings();
// update group membership, join and remove from given groups
// sync group membership for this user
if (groupMappings.size() > 0) {
// flag if always sync or just on create of the user
String syncmode = configuration.getLDAPParam("ldap_mode_group_sync", "always");
if (!syncmode.equalsIgnoreCase("create") || createuser) {
syncGroupsMembership(xwikiUserName, ldapDn, groupMappings, ldapUtils, context);
}
}
}
/**
* Synchronize user XWiki membership with it's LDAP membership.
*
* @param xwikiUserName the name of the user.
* @param userDN the LDAP DN of the user.
* @param groupMappings the mapping between XWiki groups names and LDAP groups names.
* @param ldapUtils the LDAP communication tool.
* @param context the XWiki context.
* @throws XWikiException error when synchronizing user membership.
*/
protected void syncGroupsMembership(String xwikiUserName, String userDN, Map<String, Set<String>> groupMappings,
XWikiLDAPUtils ldapUtils, XWikiContext context) throws XWikiException
{
ldapUtils.syncGroupsMembership(xwikiUserName, userDN, groupMappings, context);
}
}