KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > repo > security > authentication > ntlm > NTLMAuthenticationComponentImpl


1 /*
2  * Copyright (C) 2006 Alfresco, Inc.
3  *
4  * Licensed under the Mozilla Public License version 1.1
5  * with a permitted attribution clause. You may obtain a
6  * copy of the License at
7  *
8  * http://www.alfresco.org/legal/license.txt
9  *
10  * Unless required by applicable law or agreed to in writing,
11  * software distributed under the License is distributed on an
12  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13  * either express or implied. See the License for the specific
14  * language governing permissions and limitations under the
15  * License.
16  */

17 package org.alfresco.repo.security.authentication.ntlm;
18
19 import java.io.IOException JavaDoc;
20 import java.net.InetAddress JavaDoc;
21 import java.net.UnknownHostException JavaDoc;
22 import java.security.NoSuchAlgorithmException JavaDoc;
23 import java.security.Provider JavaDoc;
24 import java.security.Security JavaDoc;
25 import java.util.Enumeration JavaDoc;
26 import java.util.Hashtable JavaDoc;
27
28 import net.sf.acegisecurity.Authentication;
29 import net.sf.acegisecurity.AuthenticationServiceException;
30 import net.sf.acegisecurity.BadCredentialsException;
31 import net.sf.acegisecurity.CredentialsExpiredException;
32 import net.sf.acegisecurity.GrantedAuthority;
33 import net.sf.acegisecurity.GrantedAuthorityImpl;
34
35 import org.alfresco.error.AlfrescoRuntimeException;
36 import org.alfresco.filesys.server.auth.PasswordEncryptor;
37 import org.alfresco.filesys.server.auth.passthru.AuthenticateSession;
38 import org.alfresco.filesys.server.auth.passthru.PassthruServers;
39 import org.alfresco.filesys.smb.SMBException;
40 import org.alfresco.filesys.smb.SMBStatus;
41 import org.alfresco.model.ContentModel;
42 import org.alfresco.repo.security.authentication.AbstractAuthenticationComponent;
43 import org.alfresco.repo.security.authentication.AuthenticationException;
44 import org.alfresco.repo.security.authentication.NTLMMode;
45 import org.alfresco.service.cmr.repository.NodeRef;
46 import org.alfresco.service.cmr.repository.NodeService;
47 import org.alfresco.service.cmr.security.PersonService;
48 import org.apache.commons.logging.Log;
49 import org.apache.commons.logging.LogFactory;
50
51 /**
52  * NTLM Authentication Component Class
53  *
54  * <p>Provides authentication using passthru to a Windows server(s)/domain controller(s) using the accounts
55  * defined on the passthru server to validate users.
56  *
57  * @author GKSpencer
58  */

59 public class NTLMAuthenticationComponentImpl extends AbstractAuthenticationComponent
60 {
61     // Logging
62

63     private static final Log logger = LogFactory.getLog("org.alfresco.passthru.auth");
64
65     // Constants
66
//
67
// Standard authorities
68

69     public static final String JavaDoc NTLMAuthorityGuest = "Guest";
70     public static final String JavaDoc NTLMAuthorityAdministrator = "Administrator";
71     
72     // Active session timeout
73

74     private static final long DefaultSessionTimeout = 60000L; // 1 minute
75
private static final long MinimumSessionTimeout = 5000L; // 5 seconds
76

77     // Passthru authentication servers
78

79     private PassthruServers m_passthruServers;
80     
81     // Password encryptor for generating password hash for local authentication
82

83     private PasswordEncryptor m_encryptor;
84     
85     // Allow guest access
86

87     private boolean m_allowGuest;
88     
89     // Table of currently active passthru authentications and the associated authentication session
90
//
91
// If the two authentication stages are not completed within a reasonable time the authentication
92
// session will be closed by the reaper thread.
93

94     private Hashtable JavaDoc<NTLMPassthruToken,AuthenticateSession> m_passthruSessions;
95     
96     // Active authentication session timeout, in milliseconds
97

98     private long m_passthruSessTmo = DefaultSessionTimeout;
99     
100     // Authentication session reaper thread
101

102     private PassthruReaperThread m_reaperThread;
103     
104     // Person service, used to map passthru usernames to Alfresco person names
105

106     private PersonService m_personService;
107     private NodeService m_nodeService;
108     
109     /**
110      * Passthru Session Reaper Thread
111      */

112     class PassthruReaperThread extends Thread JavaDoc
113     {
114         // Thread shutdown request flag
115

116         private boolean m_ishutdown;
117
118         // Reaper wakeup interval, in milliseconds
119

120         private long m_wakeupInterval = m_passthruSessTmo / 2;
121         
122         /**
123          * Default constructor
124          */

125         PassthruReaperThread()
126         {
127             setDaemon(true);
128             setName("PassthruReaper");
129             start();
130         }
131         
132         /**
133          * Set the wakeup interval
134          *
135          * @param wakeup long
136          */

137         public final void setWakeup(long wakeup)
138         {
139             m_wakeupInterval = wakeup;
140         }
141         
142         /**
143          * Main thread code
144          */

145         public void run()
146         {
147             // Loop until shutdown
148

149             m_ishutdown = false;
150             
151             while ( m_ishutdown == false)
152             {
153                 // Sleep for a while
154

155                 try
156                 {
157                     sleep( m_wakeupInterval);
158                 }
159                 catch ( InterruptedException JavaDoc ex)
160                 {
161                 }
162                 
163                 // Check if there are any active sessions to check
164

165                 if ( m_passthruSessions.size() > 0)
166                 {
167                     // Enumerate the active sessions
168

169                     Enumeration JavaDoc<NTLMPassthruToken> tokenEnum = m_passthruSessions.keys();
170                     long timeNow = System.currentTimeMillis();
171                     
172                     while (tokenEnum.hasMoreElements())
173                     {
174                         // Get the current NTLM token and check if it has expired
175

176                         NTLMPassthruToken ntlmToken = tokenEnum.nextElement();
177                         
178                         if ( ntlmToken != null && ntlmToken.getAuthenticationExpireTime() < timeNow)
179                         {
180                             // Authentication token has expired, close the associated authentication session
181

182                             AuthenticateSession authSess = m_passthruSessions.get(ntlmToken);
183                             if ( authSess != null)
184                             {
185                                 try
186                                 {
187                                     // Close the authentication session
188

189                                     authSess.CloseSession();
190                                 }
191                                 catch ( Exception JavaDoc ex)
192                                 {
193                                     // Debug
194

195                                     if(logger.isDebugEnabled())
196                                         logger.debug("Error closing expired authentication session", ex);
197                                 }
198                             }
199                             
200                             // Remove the expired token from the active list
201

202                             m_passthruSessions.remove(ntlmToken);
203                             
204                             // Debug
205

206                             if(logger.isDebugEnabled())
207                                 logger.debug("Removed expired NTLM token " + ntlmToken);
208                         }
209                     }
210                 }
211             }
212             
213             // Debug
214

215             if(logger.isDebugEnabled())
216                 logger.debug("Passthru reaper thread shutdown");
217         }
218         
219         /**
220          * Shutdown the reaper thread
221          */

222         public final void shutdownRequest()
223         {
224             m_ishutdown = true;
225             this.interrupt();
226         }
227     }
228
229     /**
230      * Class constructor
231      */

232     public NTLMAuthenticationComponentImpl() {
233         
234         // Create the passthru authentication server list
235

236         m_passthruServers = new PassthruServers();
237         
238         // Create the password encryptor for local password hashing
239

240         m_encryptor = new PasswordEncryptor();
241         
242         // Create the active session list and reaper thread
243

244         m_passthruSessions = new Hashtable JavaDoc<NTLMPassthruToken,AuthenticateSession>();
245         m_reaperThread = new PassthruReaperThread();
246     }
247
248     /**
249      * Determine if guest logons are allowed
250      *
251      * @return boolean
252      */

253     public final boolean allowsGuest()
254     {
255         return m_allowGuest;
256     }
257     
258     /**
259      * Set the domain to authenticate against
260      *
261      * @param domain String
262      */

263     public void setDomain(String JavaDoc domain) {
264         
265         // Check if the passthru server list is already configured
266

267         if ( m_passthruServers.getTotalServerCount() > 0)
268             throw new AlfrescoRuntimeException("Passthru server list already configured");
269         
270         // Configure the passthru authentication server list using the domain controllers
271

272         m_passthruServers.setDomain(domain);
273     }
274     
275     /**
276      * Set the server(s) to authenticate against
277      *
278      * @param servers String
279      */

280     public void setServers(String JavaDoc servers) {
281         
282         // Check if the passthru server list is already configured
283

284         if ( m_passthruServers.getTotalServerCount() > 0)
285             throw new AlfrescoRuntimeException("Passthru server list already configured");
286         
287         // Configure the passthru authenticaiton list using a list of server names/addresses
288

289         m_passthruServers.setServerList(servers);
290     }
291     
292     /**
293      * Use the local server as the authentication server
294      *
295      * @param useLocal String
296      */

297     public void setUseLocalServer(String JavaDoc useLocal)
298     {
299         // Check if the local server should be used for authentication
300

301         if ( Boolean.parseBoolean(useLocal) == true)
302         {
303             // Check if the passthru server list is already configured
304

305             if ( m_passthruServers.getTotalServerCount() > 0)
306                 throw new AlfrescoRuntimeException("Passthru server list already configured");
307
308             try
309             {
310                 // Get the list of local network addresses
311

312                 InetAddress JavaDoc[] localAddrs = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
313                 
314                 // Build the list of local addresses
315

316                 if ( localAddrs != null && localAddrs.length > 0)
317                 {
318                     StringBuilder JavaDoc addrStr = new StringBuilder JavaDoc();
319                 
320                     for ( InetAddress JavaDoc curAddr : localAddrs)
321                     {
322                         if ( curAddr.isLoopbackAddress() == false)
323                         {
324                             addrStr.append(curAddr.getHostAddress());
325                             addrStr.append(",");
326                         }
327                     }
328                     
329                     if ( addrStr.length() > 0)
330                         addrStr.setLength(addrStr.length() - 1);
331                     
332                     // Set the server list using the local address list
333

334                     m_passthruServers.setServerList(addrStr.toString());
335                 }
336                 else
337                     throw new AlfrescoRuntimeException("No local server address(es)");
338             }
339             catch ( UnknownHostException JavaDoc ex)
340             {
341                 throw new AlfrescoRuntimeException("Failed to get local address list");
342             }
343         }
344     }
345     
346     /**
347      * Allow guest access
348      *
349      * @param guest String
350      */

351     public void setGuestAccess(String JavaDoc guest)
352     {
353         m_allowGuest = Boolean.parseBoolean(guest);
354     }
355     
356     /**
357      * Set the JCE provider
358      *
359      * @param providerClass String
360      */

361     public void setJCEProvider(String JavaDoc providerClass)
362     {
363         // Set the JCE provider, required to provide various encryption/hashing algorithms not available
364
// in the standard Sun JDK/JRE
365

366         try
367         {
368
369             // Load the JCE provider class and validate
370

371             Object JavaDoc jceObj = Class.forName(providerClass).newInstance();
372             if (jceObj instanceof java.security.Provider JavaDoc)
373             {
374
375                 // Inform listeners, validate the configuration change
376

377                 Provider JavaDoc jceProvider = (Provider JavaDoc) jceObj;
378
379                 // Add the JCE provider
380

381                 Security.addProvider(jceProvider);
382                 
383                 // Debug
384

385                 if ( logger.isDebugEnabled())
386                     logger.debug("Using JCE provider " + providerClass);
387             }
388             else
389             {
390                 throw new AlfrescoRuntimeException("JCE provider class is not a valid Provider class");
391             }
392         }
393         catch (ClassNotFoundException JavaDoc ex)
394         {
395             throw new AlfrescoRuntimeException("JCE provider class " + providerClass + " not found");
396         }
397         catch (Exception JavaDoc ex)
398         {
399             throw new AlfrescoRuntimeException("JCE provider class error", ex);
400         }
401     }
402     
403     /**
404      * Set the authentication session timeout, in seconds
405      *
406      * @param sessTmo String
407      */

408     public void setSessionTimeout(String JavaDoc sessTmo)
409     {
410         // Convert to an integer value and range check the timeout value
411

412         try
413         {
414             // Convert to an integer value
415

416             long sessTmoMilli = Long.parseLong(sessTmo) * 1000L;
417             
418             if ( sessTmoMilli < MinimumSessionTimeout)
419                 throw new AlfrescoRuntimeException("Authentication session timeout too low, " + sessTmo);
420             
421             // Set the authentication session timeout value
422

423             m_passthruSessTmo = sessTmoMilli;
424             
425             // Set the reaper thread wakeup interval
426

427             m_reaperThread.setWakeup( sessTmoMilli / 2);
428         }
429         catch(NumberFormatException JavaDoc ex)
430         {
431             throw new AlfrescoRuntimeException("Invalid authenication session timeout value");
432         }
433     }
434     
435     /**
436      * Set the person service
437      *
438      * @param personService PersonService
439      */

440     public final void setPersonService(PersonService personService)
441     {
442         m_personService = personService;
443     }
444     
445     /**
446      * Set the node service
447      *
448      * @param nodeService NodeService
449      */

450     public final void setNodeService(NodeService nodeService)
451     {
452         m_nodeService = nodeService;
453     }
454     
455     /**
456      * Return the authentication session timeout, in milliseconds
457      *
458      * @return long
459      */

460     private final long getSessionTimeout()
461     {
462         return m_passthruSessTmo;
463     }
464     
465     /**
466      * Authenticate
467      *
468      * @param userName String
469      * @param password char[]
470      * @throws AuthenticationException
471      */

472     public void authenticate(String JavaDoc userName, char[] password) throws AuthenticationException
473     {
474         // Debug
475

476         if ( logger.isDebugEnabled())
477             logger.debug("Authenticate user=" + userName + " via local credentials");
478         
479         // Create a local authentication token
480

481         NTLMLocalToken authToken = new NTLMLocalToken(userName, new String JavaDoc(password));
482         
483         // Authenticate using the token
484

485         authenticate( authToken);
486         setCurrentUser( userName.toLowerCase());
487     }
488
489     /**
490      * Authenticate using a token
491      *
492      * @param token Authentication
493      * @return Authentication
494      * @throws AuthenticationException
495      */

496     public Authentication authenticate(Authentication auth) throws AuthenticationException
497     {
498         // DEBUG
499

500         if ( logger.isDebugEnabled())
501             logger.debug("Authenticate " + auth + " via token");
502         
503         // Check if the token is for passthru authentication
504

505         if( auth instanceof NTLMPassthruToken)
506         {
507             // Access the NTLM passthru token
508

509             NTLMPassthruToken ntlmToken = (NTLMPassthruToken) auth;
510             
511             // Authenticate using passthru
512

513             authenticatePassthru(ntlmToken);
514         }
515
516         // Check for a local authentication token
517

518         else if( auth instanceof NTLMLocalToken)
519         {
520             AuthenticateSession authSess = null;
521             
522             try
523             {
524
525                 // Access the NTLM token
526

527                 NTLMLocalToken ntlmToken = (NTLMLocalToken) auth;
528     
529                 // Open a session to an authentication server
530

531                 authSess = m_passthruServers.openSession();
532                 
533                 // Authenticate using the credentials supplied
534

535                 authenticateLocal(ntlmToken, authSess);
536             }
537             finally
538             {
539                 // Make sure the authentication session is closed
540

541                 if ( authSess != null)
542                 {
543                     try
544                     {
545                         authSess.CloseSession();
546                     }
547                     catch ( Exception JavaDoc ex)
548                     {
549                     }
550                 }
551             }
552         }
553         else
554         {
555             // Unsupported authentication token
556

557             throw new AuthenticationException("Unsupported authentication token type");
558         }
559
560         // Return the updated authentication token
561

562         return getCurrentAuthentication();
563     }
564     
565     /**
566      * Get the enum that describes NTLM integration
567      *
568      * @return NTLMMode
569      */

570     public NTLMMode getNTLMMode()
571     {
572         return NTLMMode.PASS_THROUGH;
573     }
574
575     /**
576      * Get the MD4 password hash, as required by NTLM based authentication methods.
577      *
578      * @param userName String
579      * @return String
580      */

581     public String JavaDoc getMD4HashedPassword(String JavaDoc userName)
582     {
583         // Do not support MD4 hashed password
584

585         throw new AlfrescoRuntimeException("MD4 passwords not supported");
586     }
587     
588     /**
589      * Authenticate a user using local credentials
590      *
591      * @param ntlmToken NTLMLocalToken
592      * @param authSess AuthenticateSession
593      */

594     private void authenticateLocal(NTLMLocalToken ntlmToken, AuthenticateSession authSess)
595     {
596         try
597         {
598             // Get the plaintext password and generate an NTLM1 password hash
599

600             String JavaDoc username = (String JavaDoc) ntlmToken.getPrincipal();
601             String JavaDoc plainPwd = (String JavaDoc) ntlmToken.getCredentials();
602             byte[] ntlm1Pwd = m_encryptor.generateEncryptedPassword( plainPwd, authSess.getEncryptionKey(), PasswordEncryptor.NTLM1);
603             
604             // Send the logon request to the authentication server
605
//
606
// Note: Only use the stronger NTLM hash, we do not send the LM hash
607

608             authSess.doSessionSetup(username, null, ntlm1Pwd);
609             
610             // Check if the session has logged on as a guest
611

612             if ( authSess.isGuest() || username.equalsIgnoreCase("GUEST"))
613             {
614                 // If guest access is enabled add a guest authority to the token
615

616                 if ( allowsGuest())
617                 {
618                     // Set the guest authority
619

620                     GrantedAuthority[] authorities = new GrantedAuthority[2];
621                     authorities[0] = new GrantedAuthorityImpl(NTLMAuthorityGuest);
622                     authorities[1] = new GrantedAuthorityImpl("ROLE_AUTHENTICATED");
623                     
624                     ntlmToken.setAuthorities(authorities);
625                 }
626                 else
627                 {
628                     // Guest access not allowed
629

630                     throw new AuthenticationException("Guest logons disabled");
631                 }
632             }
633             else
634             {
635                 // Set authorities
636

637                 GrantedAuthority[] authorities = new GrantedAuthority[1];
638                 authorities[0] = new GrantedAuthorityImpl("ROLE_AUTHENTICATED");
639                 
640                 ntlmToken.setAuthorities(authorities);
641             }
642             
643             // Indicate that the token is authenticated
644

645             ntlmToken.setAuthenticated(true);
646             
647             // Map the passthru username to an Alfresco person
648

649             NodeRef userNode = m_personService.getPerson(username);
650             if ( userNode != null)
651             {
652                 // Get the person name and use that as the current user to line up with permission checks
653

654                 String JavaDoc personName = (String JavaDoc) m_nodeService.getProperty(userNode, ContentModel.PROP_USERNAME);
655                 setCurrentUser(personName);
656                 
657                 // DEBUG
658

659                 if ( logger.isDebugEnabled())
660                     logger.debug("Setting current user using person " + personName + " (username " + username + ")");
661             }
662             else
663             {
664                 // Set using the user name, lowercase the name if hte person service is case insensitive
665

666                 if ( m_personService.getUserNamesAreCaseSensitive() == false)
667                     username = username.toLowerCase();
668                 setCurrentUser( username);
669                 
670                 // DEBUG
671

672                 if ( logger.isDebugEnabled())
673                     logger.debug("Setting current user using username " + username);
674             }
675             
676             // Debug
677

678             if ( logger.isDebugEnabled())
679                 logger.debug("Authenticated token=" + ntlmToken);
680         }
681         catch (NoSuchAlgorithmException JavaDoc ex)
682         {
683             // JCE provider does not have the required encryption/hashing algorithms
684

685             throw new AuthenticationServiceException("JCE provider error", ex);
686         }
687         catch (IOException JavaDoc ex)
688         {
689             // Error connecting to the authentication server
690

691             throw new AuthenticationServiceException("I/O error", ex);
692         }
693         catch (SMBException ex)
694         {
695             // Check the returned status code to determine why the logon failed and throw an appropriate exception
696

697             if ( ex.getErrorClass() == SMBStatus.NTErr)
698             {
699                 AuthenticationException authEx = null;
700                 
701                 switch( ex.getErrorCode())
702                 {
703                 case SMBStatus.NTLogonFailure:
704                     authEx = new AuthenticationException("Logon failure");
705                     break;
706                 case SMBStatus.NTAccountDisabled:
707                     authEx = new AuthenticationException("Account disabled");
708                     break;
709                 default:
710                     authEx = new AuthenticationException("Logon failure");
711                 break;
712                 }
713                 
714                 throw authEx;
715             }
716             else
717                 throw new AuthenticationException("Logon failure");
718         }
719     }
720     
721     /**
722      * Authenticate using passthru authentication with a client
723      *
724      * @param ntlmToken NTLMPassthruToken
725      */

726     private void authenticatePassthru(NTLMPassthruToken ntlmToken)
727     {
728         // Check if the token has an authentication session, if not then it is either a new token
729
// or the session has been timed out
730

731         AuthenticateSession authSess = m_passthruSessions.get(ntlmToken);
732         
733         if ( authSess == null)
734         {
735             // Check if the token has a challenge, if it does then the associated session has been
736
// timed out
737

738             if ( ntlmToken.getChallenge() != null)
739                 throw new CredentialsExpiredException("Authentication session expired");
740             
741             // Open an authentication session for the new token and add to the active session list
742

743             authSess = m_passthruServers.openSession();
744             
745             ntlmToken.setAuthenticationExpireTime(System.currentTimeMillis() + getSessionTimeout());
746             
747             // Get the challenge from the initial session negotiate stage
748

749             ntlmToken.setChallenge(new NTLMChallenge(authSess.getEncryptionKey()));
750
751             StringBuilder JavaDoc details = new StringBuilder JavaDoc();
752
753             // Build a details string with the authentication session details
754

755             details.append(authSess.getDomain());
756             details.append("\\");
757             details.append(authSess.getPCShare().getNodeName());
758             details.append(",");
759             details.append(authSess.getSession().getProtocolName());
760             
761             ntlmToken.setDetails(details.toString());
762
763             // Put the token/session into the active session list
764

765             m_passthruSessions.put(ntlmToken, authSess);
766             
767             // Debug
768

769             if ( logger.isDebugEnabled())
770                 logger.debug("Passthru stage 1 token " + ntlmToken);
771         }
772         else
773         {
774             try
775             {
776                 // Stage two of the authentication, send the hashed password to the authentication server
777

778                 byte[] lmPwd = null;
779                 byte[] ntlmPwd = null;
780                 
781                 if ( ntlmToken.getPasswordType() == PasswordEncryptor.LANMAN)
782                     lmPwd = ntlmToken.getHashedPassword();
783                 else if ( ntlmToken.getPasswordType() == PasswordEncryptor.NTLM1)
784                     ntlmPwd = ntlmToken.getHashedPassword();
785                 
786                 String JavaDoc username = (String JavaDoc) ntlmToken.getPrincipal();
787                 
788                 authSess.doSessionSetup(username, lmPwd, ntlmPwd);
789                 
790                 // Check if the session has logged on as a guest
791

792                 if ( authSess.isGuest() || username.equalsIgnoreCase("GUEST"))
793                 {
794                     // If guest access is enabled add a guest authority to the token
795

796                     if ( allowsGuest())
797                     {
798                         // Set the guest authority
799

800                         GrantedAuthority[] authorities = new GrantedAuthority[1];
801                         authorities[0] = new GrantedAuthorityImpl(NTLMAuthorityGuest);
802                         
803                         ntlmToken.setAuthorities(authorities);
804                     }
805                     else
806                     {
807                         // Guest access not allowed
808

809                         throw new BadCredentialsException("Guest logons disabled");
810                     }
811                 }
812                 
813                 // Indicate that the token is authenticated
814

815                 ntlmToken.setAuthenticated(true);
816
817                 // Map the passthru username to an Alfresco person
818

819                 NodeRef userNode = m_personService.getPerson(username);
820                 if ( userNode != null)
821                 {
822                     // Get the person name and use that as the current user to line up with permission checks
823

824                     String JavaDoc personName = (String JavaDoc) m_nodeService.getProperty(userNode, ContentModel.PROP_USERNAME);
825                     setCurrentUser(personName);
826                     
827                     // DEBUG
828

829                     if ( logger.isDebugEnabled())
830                         logger.debug("Setting current user using person " + personName + " (username " + username + ")");
831                 }
832                 else
833                 {
834                     // Set using the user name, lowercase the name if the person service is case insensitive
835

836                     if ( m_personService.getUserNamesAreCaseSensitive() == false)
837                         username = username.toLowerCase();
838                     setCurrentUser( username);
839                     
840                     // DEBUG
841

842                     if ( logger.isDebugEnabled())
843                         logger.debug("Setting current user using username " + username);
844                 }
845             }
846             catch (IOException JavaDoc ex)
847             {
848                 // Error connecting to the authentication server
849

850                 throw new AuthenticationServiceException("I/O error", ex);
851             }
852             catch (SMBException ex)
853             {
854                 // Debug
855

856                 if ( logger.isDebugEnabled())
857                     logger.debug("Passthru exception, " + ex);
858                 
859                 // Check the returned status code to determine why the logon failed and throw an appropriate exception
860

861                 if ( ex.getErrorClass() == SMBStatus.NTErr)
862                 {
863                     AuthenticationException authEx = null;
864                     
865                     switch( ex.getErrorCode())
866                     {
867                     case SMBStatus.NTLogonFailure:
868                         authEx = new AuthenticationException("Logon failure");
869                         break;
870                     case SMBStatus.NTAccountDisabled:
871                         authEx = new AuthenticationException("Account disabled");
872                         break;
873                     default:
874                         authEx = new AuthenticationException("Logon failure");
875                     break;
876                     }
877                     
878                     throw authEx;
879                 }
880                 else
881                     throw new BadCredentialsException("Logon failure");
882             }
883             finally
884             {
885                 // Make sure the authentication session is closed
886

887                 if ( authSess != null)
888                 {
889                     try
890                     {
891                         // Remove the session from the active list
892

893                         m_passthruSessions.remove(ntlmToken);
894                         
895                         // Close the session to the authentication server
896

897                         authSess.CloseSession();
898                     }
899                     catch (Exception JavaDoc ex)
900                     {
901                     }
902                 }
903             }
904         }
905     }
906
907     /**
908      * Check if the user exists
909      *
910      * @param userName String
911      * @return boolean
912      */

913     public boolean exists(String JavaDoc userName)
914     {
915        throw new UnsupportedOperationException JavaDoc();
916     }
917
918     @Override JavaDoc
919     protected boolean implementationAllowsGuestLogin()
920     {
921        return allowsGuest();
922     }
923     
924     
925 }
926
Popular Tags