Wiki source code of User Authentication

Version 35.1 by Caleb James DeLisle on 2010/03/11

Show last authors
1 XWiki supports several different authentication mechanisms for authenticating users:
2
3 {{toc/}}
4
5 The form authentication is the default mechanism.
6
7 {{info}}
8 Note that currently XWiki allows only one method of authentication to be enabled at a time. This will probably be improved in the future.
9 {{/info}}
10
11 = Form Authentication =
12
13 TODO
14
15 = LDAP Authentication =
16
17 {{warning}}
18 New LDAP implementation since XWiki Platform 1.3M2, see [[previous LDAP authentication service documentation>>AuthenticationLdapOld]]
19 {{/warning}}
20
21 == Generic LDAP configuration ==
22
23 In order to enable the LDAP support you have to change the authentication method in //WEB-INF/xwiki.cfg// as follows:
24
25 {{code}}
26 ## Turn LDAP authentication on - otherwise only XWiki authentication
27 ## 0 : disable
28 ## 1 : enable
29 xwiki.authentication.ldap=1
30
31 ## set LDAP as authentication service
32 xwiki.authentication.authclass=com.xpn.xwiki.user.impl.LDAP.XWikiLDAPAuthServiceImpl
33 {{/code}}
34
35 You can setup the LDAP configuration in the //xwiki.cfg// file by filling the following properties:
36
37 {{code language="none"}}
38 ## LDAP Server (Active Directory, eDirectory, OpenLDAP, etc.)
39 xwiki.authentication.ldap.server=156.58.101.204
40 xwiki.authentication.ldap.port=389
41
42 ## LDAP login, empty = anonymous access, otherwise specify full dn
43 ## {0} is replaced with the username, {1} with the password
44 xwiki.authentication.ldap.bind_DN=cn={0},department=USER,department=INFORMATIK,department=1230,o=MP
45 xwiki.authentication.ldap.bind_pass={1}
46
47 ## Force to check password after LDAP connection
48 ## 0: disable
49 ## 1: enable
50 xwiki.authentication.ldap.validate_password=0
51
52 ## only members of the following group will be verified in the LDAP
53 ## otherwise only users that are found after searching starting from the base_DN
54 xwiki.authentication.ldap.user_group=cn=developers,ou=groups,o=MegaNova,c=US
55
56 ## only users not member of the following group can autheticate
57 xwiki.authentication.ldap.exclude_group=cn=admin,ou=groups,o=MegaNova,c=US
58
59 ## base DN for searches
60 xwiki.authentication.ldap.base_DN=
61 department=USER,department=INFORMATIK,department=1230,o=MP
62
63 ## specifies the LDAP attribute containing the identifier to be used as the XWiki name (default=cn)
64 xwiki.authentication.ldap.UID_attr=cn
65
66 ## retrieve the following fields from LDAP and store them in the XWiki user object (xwiki-attribute=ldap-attribute)
67 xwiki.authentication.ldap.fields_mapping=last_name=sn,first_name=givenName,fullname=fullName,email=mail
68
69 # on every login update the mapped attributes from LDAP to XWiki otherwise this happens only once when the XWiki account is created.
70 xwiki.authentication.ldap.update_user=1
71
72 ## maps XWiki groups to LDAP groups, separator is "|"
73 xwiki.authentication.ldap.group_mapping=XWiki.XWikiAdminGroup=cn=AdminRole,ou=groups,o=MegaNova,c=US|\
74 XWiki.Organisation=cn=testers,ou=groups,o=MegaNova,c=US
75
76 ## time in seconds after which the list of members in a group is refreshed from LDAP (default=3600*6)
77 xwiki.authentication.ldap.groupcache_expiration=21800
78
79 ## - create : synchronize group membership only when the user is first created
80 ## - always: synchronize on every login
81 xwiki.authentication.ldap.mode_group_sync=always
82
83 ## if ldap authentication fails for any reason, try XWiki DB authentication with the same credentials
84 xwiki.authentication.ldap.trylocal=1
85
86 ## SSL connection to LDAP server
87 ## 0 : normal
88 ## 1 : SSL
89 xwiki.authentication.ldap.ssl=1
90
91 ## The keystore file to use in SSL connection
92 xwiki.authentication.ldap.ssl.keystore=
93 {{/code}}
94
95 {{info}}
96 You can also setup the LDAP configuration in XWiki.XWikiPreferences page by going to the object editor. Simply replace "xwiki.authentication.ldap." by "ldap_". For example ##xwiki.authentication.ldap.base_DN## becomes ##ldap_base_DN##
97 {{/info}}
98
99 For testing purposes, you may wish to omit the "ldap.fields_mapping" field, to test the authentication first, and then add it later to get the mappings right.
100
101 Here are some LDAP client for checking your configuration:
102
103 * [[Apache Directory Studio>>http://directory.apache.org/studio/]]
104 * [[LDAP Browser/Editor>>http://www-unix.mcs.anl.gov/gawor/ldap/]]
105
106 == Detailed use cases ==
107
108 See [[LDAP configuration uses cases>>LDAPAuthenticationUseCases]] for some detailed use cases.
109
110 == Enable LDAP debug log ==
111
112 See [[AdminGuide.Logging]]. The specific targets for LDAP authentication are:
113
114 {{code}}
115 log4j.logger.com.xpn.xwiki.plugin.ldap=debug
116 log4j.logger.com.xpn.xwiki.user.impl.LDAP=debug
117 {{/code}}
118
119 = eXo Authentication =
120
121 The eXo authentication is used automatically by adding/editing the //xwiki.exo=1// property in //WEB-INF/xwiki.cfg//.
122
123 = Custom Authentication =
124
125 This allows plugging to any existing authentication mechanism such as SiteMinder, etc. To configure a custom authentication do the following:
126
127 1. Implement the [[XWikiAuthService>>http://svn.xwiki.org/svnroot/xwiki/platform/core/trunk/xwiki-core/src/main/java/com/xpn/xwiki/user/api/XWikiAuthService.java]] interface.
128 1. Edit the //WEB-INF/xwiki.cfg// file and add a //xwiki.authentication.authclass// property pointing to your class. For example:
129
130 {{code}}
131 xwiki.authentication.authclass = com.acme.MyCustomAuthenticationService
132 {{/code}}
133
134 Here's a [[tutorial on implementing a custom authentication class for authenticating against Oracle's SSO>>http://bodez.wordpress.com/2008/10/15/xwiki-user-authentication-with-oracle-sso/]].
135
136 Note, that you also can implement own right management service by implementing [[XWikiRightService>>http://svn.xwiki.org/svnroot/xwiki/platform/core/trunk/xwiki-core/src/main/java/com/xpn/xwiki/user/api/XWikiRightService.java]] interface:
137
138 {{code}}
139 xwiki.authentication.rightsclass = com.acme.MyCustomRightsService
140 {{/code}}
141
142 and Group Service by implementing [[XWikiGroupService>>http://svn.xwiki.org/svnroot/xwiki/platform/core/trunk/xwiki-core/src/main/java/com/xpn/xwiki/user/api/XWikiGroupService.java]]:
143
144 {{code}}
145 xwiki.authentication.groupclass = com.acme.MyCustomGroupService
146 {{/code}}
147
148 == Custom Authentication using a Groovy script in a wiki page ==
149
150 Start by specifying you want to use the Groovy Authenticator:
151
152 {{code}}
153 xwiki.authentication.authclass = com.xpn.xwiki.user.impl.xwiki.GroovyAuthServiceImpl
154 {{/code}}
155
156 Then add another configuration parameter to specify in which wiki page the authenticator is:
157
158 {{code}}
159 xwiki.authentication.groovy.pagename = MySpace.MyPage
160 {{/code}}
161
162 Then in a wiki page put some Groovy code that returns a XWikiAuthService object.
163
164 = Authentication parameters ===
165
166 You can set each of these parameters by setting:
167
168 {{code}}
169 xwiki.authentication.~~param_name~~=~~param_value~~
170 {{/code}}
171
172 |=Name|=Optional|=Allowed values|=Default value|=Description
173 |encryptionKey|No(1)|?|n/a|Set the Encryption Key used to create a secret key, the secret key is passed to the Cipher object to be used during encryption and decryption of cookie values.
174 |validationKey|No(2)|?|n/a|Set the Validation Key used to generate hash value; the hash value is stored with the cookie and used to verify that the cookie has not been tampered with.
175 |cookiedomains|Yes|String|Server host name|Which host(s) should your cookies be sent to; use only if you want to share cookies across domains, otherwise should be commented out
176 |cookielife|Yes|Number|14|Number of days cookies take to expire
177 |cookiepath|Yes|String|/|The webapp path that XWiki cookies should be sent to; if you have anything else running on your web server, this should be set to ///xwiki//
178 |default_page|Yes|String|/bin/view/ Main/WebHome|Page to redirect to if xredirect parameter is not set
179 |encryptionalgorithm|Yes|?|?|Set the Encryption Algorithm used to encrypt and decrypt cookies
180 |encryptionmode|Yes|?|?|Set the Encryption Mode used to encrypt and decrypt cookies
181 |encryptionpadding|Yes|?|?|Set the Encryption Padding used to encrypt and decrypt cookies
182 |errorpage|Yes|String|/bin/loginerror/ XWiki/XWikiLogin|Page to redirect to if there is an error logging in
183 |loginpage|Yes|String|/bin/login/ XWiki/XWikiLogin|Page to redirect to when not logged in
184 |loginsubmitpage|Yes|String|/loginsubmit/ XWiki/XWikiLogin|The URL where the username and password are posted to when logging in.
185 |logoutpage|Yes|String|/bin/logout/ XWiki/XWikiLogout|Page to redirect to after logged out
186 |realmname|Yes|String|XWiki|Sets the realm name
187 |protection|Yes|all, validation, encryption, none|all|Protection level for the "remember me" cookie functionality
188 |unauthorized_code|Yes|Number|401|The HTTP status code to return when the login has failed.
189 |useip|Yes|true / false|true|Specify to use the IP address when encrypting the cookie data; if IP address changes will need to re-login.
190
191 1. Only required if protection = encryption or all (default)
192 1. Only required if protection = validation or all (default)
193
194 = Kerberos SSO Authentication =
195
196 {{warning}}
197 This implementation of SSO is currently under review see: http://jira.xwiki.org/jira/browse/XWIKI-2496 . The class which is described in this segment of documentation, AppServerTrustedKerberosAuthServiceImpl, is not part of the default XWiki distribution!
198 {{/warning}}
199
200 The following is an example of mod_auth_kerb for Apache being used to easily implement Xwiki authentication of users via by HTTP Negotiate on a linux server. This example assumes you already have a working Apache2 HTTPD and Apache Tomcat setup with mod_jk.
201
202 First of all you need to create a principal and keytab for the webserver:
203
204 {{code}}
205 # kadmin
206 kadmin> addprinc -randkey HTTP/wiki.example.com
207 kadmin> ktadd -k /etc/apache2/ssl/wiki.keytab HTTP/wiki.example.com
208 kadmin> quit
209 {{/code}}
210
211 Make sure the keytab has the right permissions and ownership:
212
213 {{code}}
214 chown www-data:www-data /etc/apache2/ssl/wiki.keytab
215 chmod 400 /etc/apache2/ssl/wiki.keytab
216 {{/code}}
217
218 Install mod_auth_kerb in your linux installation. On Debian or Ubuntu this would be achieved by running:
219
220 {{code}}
221 aptitude install libapache2-mod-auth-kerb
222 {{/code}}
223
224 Of course the installation procedure varies per Linux distribution.
225
226 If your xwiki installation is mounted in Apache HTTPD under /xwiki, add the following to the virtual host configuration:
227
228 {{code}}
229 <Location /xwiki/>
230 AuthType Kerberos
231 AuthName "Kerberos Login"
232 KrbAuthRealms EXAMPLE.COM
233 Krb5Keytab "/etc/apache2/ssl/wiki.keytab"
234 KrbMethodK5Passwd off
235 KrbMethodNegotiate on
236 KrbSaveCredentials on
237 require valid-user
238 </Location>
239 {{/code}}
240
241 Make sure Apache Tomcat uses the authentication performed by Apache HTTPD with the "tomcatAuthentication" property in the connector description (which is in the server.xml file of Apache Tomcat):
242
243 {{code}}
244 <Connector port="8009" address="127.0.0.1" enableLookups="false" tomcatAuthentication="false" redirectPort="8443" protocol="AJP/1.3" />
245 {{/code}}
246
247 Place the authkerb.jar jar in the WEB-INF/lib directory of Xwiki in Apache Tomcat.
248
249 Have Xwiki use the authentication module by changing the "xwiki.authentication.authclass" property in WEB-INF/lib/xwiki.cfg file.
250
251 {{code}}
252 xwiki.authentication.authclass=com.xpn.xwiki.user.impl.xwiki.AppServerTrustedKerberosAuthServiceImpl
253 {{/code}}
254
255 If you use Firefox, do not forget to whitelist the xwiki URL for HTTP Negotiate in about:config with the "network.negotiate-auth.trusted-uris" property. possible values for this propperty include (without the quotes): "https:~/~/" for all secured connections or "example.com" for all example.com subdomains.
256
257 2 JBoss SPNEGO (Kerberos in combination with LDAP) I changed the code of the XWikiLDAPAuthServiceImpl to be able to detect the sso user. The authenication already happend by using the SPNEGO module (JAAS). After that I'm using the ldap synchronisation feature to make sure that the user is up to date. The combination leads to an automatic login in the xwiki and the user rights are controlled in the Active Directory server. I hope you can adopt this code or that you can use it for your own projects.
258
259 The configuration of ldap:
260
261 {{code}}
262 xwiki.authentication.authclass=com.wiki.sso.SSOLdapAuthenicationImpl
263 xwiki.authentication.ldap=1
264 xwiki.authentication.ldap.server=<ad-server>
265 xwiki.authentication.ldap.port=389
266 xwiki.authentication.ldap.base_DN=<OU=Users,...............>
267 #use a fixed user to attach to the ldap database,
268 #the password is not provided with the SSOLdapAuthenicationImpl
269 xwiki.authentication.ldap.bind_DN=<domain>\\<user>
270 xwiki.authentication.ldap.bind_pass=<password>
271 #Microsoft AD configuration
272 xwiki.authentication.ldap.UID_attr=sAMAccountName
273 xwiki.authentication.ldap.fields_mapping=name=sAMAccountName,last_name=sn,first_name=givenName,fullname=displayName,mail=mail,ldap_dn=dn
274 xwiki.authentication.ldap.group_memberfields=member,uniqueMember
275 #LDAP group mapping
276 xwiki.authentication.ldap.group_mapping=XWiki.XWikiAdminGroup=CN=WIKI_Admin,............|\
277 XWiki.XWikiAllGroup=CN=WIKI_User,...........
278 {{/code}}
279
280 The java code
281
282 {{code}}
283 package com.wiki.sso;
284
285
286 import org.apache.commons.logging.Log;
287 import org.apache.commons.logging.LogFactory;
288
289 import com.xpn.xwiki.XWikiContext;
290 import com.xpn.xwiki.XWikiException;
291 import com.xpn.xwiki.user.api.XWikiUser;
292 import com.xpn.xwiki.user.impl.LDAP.XWikiLDAPAuthServiceImpl;
293
294 import java.security.Principal;
295
296 public class SSOLdapAuthenicationImpl extends XWikiLDAPAuthServiceImpl {
297 /**
298 * Logging tool.
299 */
300 private static final Log LOG = LogFactory.getLog(SSOLdapAuthenicationImpl.class);
301
302
303 public XWikiUser checkAuth(XWikiContext context) throws XWikiException {
304 String user = getRemoteUser(context);
305 if ((user != null) || !user.equals("")) {
306 if (LOG.isInfoEnabled())
307 LOG.info("Launching create user for " + user);
308 if ( authenticate(user, context) != null ) {
309 if (LOG.isInfoEnabled())
310 LOG.info("Create user done for " + user);
311 user = "XWiki." + user;
312 context.setUser(user);
313 System.out.println("User is set to:" + user);
314 return new XWikiUser(user);
315 } else {
316 LOG.error( "User " + user + " can't be authenticated against ldap" );
317 }
318 }
319 return super.checkAuth(context);
320 }
321
322 /**
323 * We cannot authenticate locally since we need to trust the app server for
324 * authentication
325 *
326 * @param username
327 * @param password
328 * @param context
329 * @return
330 * @throws XWikiException
331 */
332 public XWikiUser checkAuth(String username, String password,
333 String rememberme, XWikiContext context) throws XWikiException {
334 String user = getRemoteUser(context);
335 if ((user == null) || user.equals("")) {
336 return super.checkAuth(username, password, rememberme, context);
337 }
338 return checkAuth(context);
339 }
340
341 private String getRemoteUser(XWikiContext context) {
342 String userName = context.getRequest().getHttpServletRequest()
343 .getRemoteUser();
344 if (userName != null) {
345 // only take the front of the username@domain
346 String[] elements = userName.split("@", 2);
347 userName = elements[0];
348 }
349 return userName;
350 }
351
352 public Principal authenticate(String login, XWikiContext context) throws XWikiException
353 {
354 if (LOG.isTraceEnabled()) {
355 LOG.trace("Starting LDAP authentication");
356 }
357
358 /*
359 * TODO: Put the next 4 following "if" in common with XWikiAuthService to ensure coherence This method was
360 * returning null on failure so I preserved that behaviour, while adding the exact error messages to the context
361 * given as argument. However, the right way to do this would probably be to throw XWikiException-s.
362 */
363
364 if (login == null) {
365 // If we can't find the username field then we are probably on the login screen
366
367 if (LOG.isDebugEnabled()) {
368 LOG.debug("The provided user is null."
369 + " We don't try to authenticate, it probably means the user is in non logged mode.");
370 }
371
372 return null;
373 }
374
375 // Check for empty usernames
376 if (login.equals("")) {
377 context.put("message", "nousername");
378
379 if (LOG.isDebugEnabled()) {
380 LOG.debug("LDAP authentication failed: login empty");
381 }
382
383 return null;
384 }
385
386 // If we have the context then we are using direct mode
387 // then we should specify the database
388 // This is needed for virtual mode to work
389 Principal principal = null;
390
391 // Try authentication against ldap
392 principal = ldapAuthenticate(login, "", context);
393
394 if (LOG.isDebugEnabled()) {
395 if (principal != null) {
396 LOG.debug("LDAP authentication succeed with principal [" + principal.getName() + "]");
397 } else {
398 LOG.debug("LDAP authentication failed for user [" + login + "]");
399 }
400 }
401
402 return principal;
403 }
404 }
405 {{/code}}

Get Connected