Guest User

Untitled

a guest
Jan 6th, 2015
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 5.21 KB | None | 0 0
  1. package ldap
  2.  
  3. import javax.naming.AuthenticationException
  4. import javax.naming.Context
  5. import javax.naming.InvalidNameException
  6. import javax.naming.NamingException
  7. import javax.naming.directory.InitialDirContext
  8. import javax.persistence.NoResultException
  9.  
  10. import net.datenwerke.rs.authenticator.client.login.dto.UserPasswordAuthToken
  11. import net.datenwerke.rs.authenticator.client.login.pam.UserPasswordClientPAM
  12. import net.datenwerke.rs.utils.crypto.PasswordHasher;
  13. import net.datenwerke.security.client.login.AuthToken
  14. import net.datenwerke.security.service.authenticator.AuthenticationResult
  15. import net.datenwerke.security.service.authenticator.ReportServerPAM
  16. import net.datenwerke.security.service.authenticator.hooks.PAMHook
  17. import net.datenwerke.security.service.usermanager.UserManagerService
  18. import net.datenwerke.security.service.usermanager.entities.User
  19.  
  20. import com.google.inject.Inject
  21.  
  22.  
  23. final LdapPAM ldapPam = GLOBALS.injector.getInstance(LdapPAM.class);
  24. GLOBALS.services.callbackRegistry.attachHook("LDAP_PAM", PAMHook.class, new PAMHook(){
  25.    
  26.     public void beforeStaticPamConfig(LinkedHashSet<ReportServerPAM> pams){
  27.         pams.add(ldapPam);
  28.     }
  29.     public void afterStaticPamConfig(LinkedHashSet<ReportServerPAM> pams){
  30.        
  31.     }
  32.    
  33. });
  34.  
  35.  
  36. public class LdapPAM implements ReportServerPAM {
  37.    
  38.     private static final String CLIENT_MODULE_NAME = UserPasswordClientPAM.class.getName();
  39.     private UserManagerService userManagerService;
  40.     private PasswordHasher passwordHasher;
  41.    
  42.     @Inject
  43.     public LdapPAM(UserManagerService userManagerService, PasswordHasher passwordHasher) {
  44.         this.userManagerService = userManagerService;
  45.         this.passwordHasher = passwordHasher;
  46.     }
  47.    
  48.    
  49.     public AuthenticationResult authenticate(AuthToken[] tokens) {
  50.         for(Object token : tokens){
  51.             if(token instanceof UserPasswordAuthToken){
  52.                 UserPasswordAuthToken credentials = (UserPasswordAuthToken) token;
  53.                 User u = authenticate(credentials.getUsername(), credentials.getPassword());
  54.                 if(null != u){
  55.                     System.out.println("####### LdapPAM: authenticate success (usr=" + u.getUsername() + ")")
  56.                     return new AuthenticationResult(true, u, true);
  57.                 }else{
  58.                     User usr = getUserOrNull(credentials.getUsername());
  59.                     boolean authoritive = (null == usr || (null != usr.getOrigin() && usr.getOrigin().toLowerCase().startsWith("ldap://")) || (null != usr.getPassword() && !usr.getPassword().isEmpty()));
  60.                     System.out.println("####### LdapPAM: authenticate failed (result=AuthenticationResult(false, " + u.getUsername() + ", "+authoritive+")")
  61.                     return new AuthenticationResult(false, usr, authoritive);
  62.                 }
  63.             }
  64.         }
  65.         System.out.println("####### LdapPAM: authenticate notoken (result=AuthenticationResult(false, null, false)")
  66.         return new AuthenticationResult(false, null, false);
  67.     }
  68.    
  69.    
  70.     protected User getUserOrNull(String username){
  71.         try{
  72.             return userManagerService.getUserByName(username);
  73.         }catch(NoResultException ex){
  74.             return null;
  75.         }
  76.     }
  77.    
  78.    
  79.     public User authenticate(String username, String cleartextPassword){
  80.         User user = getUserOrNull(username);
  81.         if(null == user)
  82.             return null;
  83.        
  84.         if(null != user.getPassword() && !user.getPassword().isEmpty() && passwordHasher.validatePassword(user.getPassword(), cleartextPassword)){
  85.             System.out.println("####### LdapPAM: authenticate with local password: success")
  86.             return user;
  87.         }else{
  88.             SSystem.out.println("####### LdapPAM: authenticate with local password: fail")
  89.         }      
  90.            
  91.         LdapAuthenticator authenticator = new LdapAuthenticator(); 
  92.         if(authenticator.authenticate(user, cleartextPassword)){
  93.             System.out.println("####### LdapPAM: authenticate against directory server: success")
  94.             return user;
  95.         }else{
  96.             System.out.println("####### LdapPAM: authenticate against directory server: failed")
  97.             return null;
  98.         }
  99.     }
  100.    
  101.     public String getClientModuleName() {
  102.         return CLIENT_MODULE_NAME;
  103.     }
  104.  
  105. }
  106.  
  107.  
  108. public class LdapAuthenticator {
  109.    
  110.     public boolean authenticate(User user, String password){
  111.         if(null == user.getOrigin() || null == user.getGuid())
  112.             return false;
  113.        
  114.         Properties props = new Properties();
  115.  
  116.         props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
  117.         props.setProperty(Context.PROVIDER_URL, getProvider(user));
  118.         props.setProperty(Context.URL_PKG_PREFIXES, "com.sun.jndi.url");
  119.         props.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
  120.  
  121.         props.setProperty(Context.SECURITY_PRINCIPAL, getPrincipal(user));
  122.         props.setProperty(Context.SECURITY_CREDENTIALS, password);
  123.        
  124.         try {
  125.             InitialDirContext ctx = new InitialDirContext(props);
  126.             ctx.getAttributes(getPrincipal(user));
  127.             return true;
  128.         } catch (AuthenticationException e) {
  129.             return false;
  130.         } catch (InvalidNameException e) {
  131.             throw new RuntimeException(e);
  132.         } catch (NamingException e) {
  133.             if(e.getMessage().contains("LdapErr: DSID-0C0906E8")){
  134.                 return false;
  135.             }
  136.            
  137.         }
  138.  
  139.     }
  140.  
  141.     private String getProvider(User user) {
  142.         String origin = user.getOrigin();
  143.         int i = origin.lastIndexOf("/");
  144.        
  145.         return origin.substring(0, i);
  146.     }
  147.  
  148.     private String getPrincipal(User user) {
  149.         String origin = user.getOrigin();
  150.            
  151.         int i = user.getOrigin().lastIndexOf("/");
  152.         return origin.substring(i + 1);
  153.     }
  154.    
  155. }
Advertisement
Add Comment
Please, Sign In to add comment