Search in sources :

Example 16 with UserPrincipal

use of org.apache.karaf.jaas.boot.principal.UserPrincipal in project karaf by apache.

the class GSSAPILdapLoginModuleTest method testSuccess.

@Test
public void testSuccess() throws Exception {
    Properties options = ldapLoginModuleOptions();
    GSSAPILdapLoginModule module = new GSSAPILdapLoginModule();
    Subject subject = new Subject();
    module.initialize(subject, new NamePasswordCallbackHandler("hnelson", "secret"), null, options);
    assertEquals("Precondition", 0, subject.getPrincipals().size());
    assertTrue(module.login());
    assertTrue(module.commit());
    assertEquals(3, subject.getPrincipals().size());
    boolean foundKrb5User = false;
    boolean foundUser = false;
    boolean foundRole = false;
    boolean foundTicket = false;
    for (Principal pr : subject.getPrincipals()) {
        if (pr instanceof KerberosPrincipal) {
            assertEquals("hnelson@EXAMPLE.COM", pr.getName());
            foundKrb5User = true;
        } else if (pr instanceof UserPrincipal) {
            assertEquals("hnelson", pr.getName());
            foundUser = true;
        } else if (pr instanceof RolePrincipal) {
            assertEquals("admin", pr.getName());
            foundRole = true;
        }
    }
    for (Object crd : subject.getPrivateCredentials()) {
        if (crd instanceof KerberosTicket) {
            assertEquals("hnelson@EXAMPLE.COM", ((KerberosTicket) crd).getClient().getName());
            assertEquals("krbtgt/EXAMPLE.COM@EXAMPLE.COM", ((KerberosTicket) crd).getServer().getName());
            foundTicket = true;
            break;
        }
    }
    assertTrue("Principals should contains kerberos user", foundKrb5User);
    assertTrue("Principals should contains ldap user", foundUser);
    assertTrue("Principals should contains ldap role", foundRole);
    assertTrue("PricatePrincipals should contains kerberos ticket", foundTicket);
    assertTrue(module.logout());
    assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) KerberosTicket(javax.security.auth.kerberos.KerberosTicket) NamePasswordCallbackHandler(org.apache.karaf.jaas.modules.NamePasswordCallbackHandler) Properties(org.apache.felix.utils.properties.Properties) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Subject(javax.security.auth.Subject) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Principal(java.security.Principal) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) AbstractKerberosITest(org.apache.directory.server.kerberos.kdc.AbstractKerberosITest) Test(org.junit.Test)

Example 17 with UserPrincipal

use of org.apache.karaf.jaas.boot.principal.UserPrincipal in project karaf by apache.

the class PropertiesBackingEngineTest method testUserRoles.

public void testUserRoles() throws IOException {
    File f = File.createTempFile(getClass().getName(), ".tmp");
    try {
        Properties p = new Properties(f);
        PropertiesBackingEngine engine = new PropertiesBackingEngine(p);
        engine.addUser("a", "aa");
        assertEquals(1, engine.listUsers().size());
        UserPrincipal upa = engine.listUsers().iterator().next();
        assertEquals("a", upa.getName());
        engine.addUser("b", "bb");
        engine.addRole("a", "role1");
        engine.addRole("a", "role2");
        assertEquals(2, engine.listRoles(upa).size());
        boolean foundR1 = false;
        boolean foundR2 = false;
        for (RolePrincipal rp : engine.listRoles(upa)) {
            if ("role1".equals(rp.getName())) {
                foundR1 = true;
            } else if ("role2".equals(rp.getName())) {
                foundR2 = true;
            }
        }
        assertTrue(foundR1);
        assertTrue(foundR2);
        engine.addGroup("a", "g");
        engine.addGroupRole("g", "role2");
        engine.addGroupRole("g", "role3");
        engine.addGroup("b", "g");
        engine.addGroup("b", "g2");
        engine.addGroupRole("g2", "role4");
        assertEquals(2, engine.listUsers().size());
        UserPrincipal upa_1 = null;
        UserPrincipal upb_1 = null;
        for (UserPrincipal u : engine.listUsers()) {
            if ("a".equals(u.getName())) {
                upa_1 = u;
            } else if ("b".equals(u.getName())) {
                upb_1 = u;
            }
        }
        assertNotNull(upa_1);
        assertNotNull(upb_1);
        assertEquals(3, engine.listRoles(upa).size());
        boolean foundR1_2 = false;
        boolean foundR2_2 = false;
        boolean foundR3_2 = false;
        for (RolePrincipal rp : engine.listRoles(upa)) {
            if ("role1".equals(rp.getName())) {
                foundR1_2 = true;
            } else if ("role2".equals(rp.getName())) {
                foundR2_2 = true;
            } else if ("role3".equals(rp.getName())) {
                foundR3_2 = true;
            }
        }
        assertTrue(foundR1_2);
        assertTrue(foundR2_2);
        assertTrue(foundR3_2);
        // check that the loading works
        PropertiesBackingEngine engine2 = new PropertiesBackingEngine(new Properties(f));
        assertEquals(2, engine2.listUsers().size());
        UserPrincipal upa_2 = null;
        UserPrincipal upb_2 = null;
        for (UserPrincipal u : engine2.listUsers()) {
            if ("a".equals(u.getName())) {
                upa_2 = u;
            } else if ("b".equals(u.getName())) {
                upb_2 = u;
            }
        }
        assertNotNull(upa_2);
        assertNotNull(upb_2);
        assertEquals(3, engine2.listRoles(upa_2).size());
        boolean foundR1_3 = false;
        boolean foundR2_3 = false;
        boolean foundR3_3 = false;
        for (RolePrincipal rp : engine2.listRoles(upa_2)) {
            if ("role1".equals(rp.getName())) {
                foundR1_3 = true;
            } else if ("role2".equals(rp.getName())) {
                foundR2_3 = true;
            } else if ("role3".equals(rp.getName())) {
                foundR3_3 = true;
            }
        }
        assertTrue(foundR1_3);
        assertTrue(foundR2_3);
        assertTrue(foundR3_3);
        assertEquals(3, engine2.listRoles(upb_2).size());
        boolean foundR2_4 = false;
        boolean foundR3_4 = false;
        boolean foundR4_4 = false;
        for (RolePrincipal rp : engine2.listRoles(upb_2)) {
            if ("role2".equals(rp.getName())) {
                foundR2_4 = true;
            } else if ("role3".equals(rp.getName())) {
                foundR3_4 = true;
            } else if ("role4".equals(rp.getName())) {
                foundR4_4 = true;
            }
        }
        assertTrue(foundR2_4);
        assertTrue(foundR3_4);
        assertTrue(foundR4_4);
        // removing some stuff
        UserPrincipal upb = null;
        for (UserPrincipal up : engine.listUsers()) {
            if ("b".equals(up.getName())) {
                upb = up;
            }
        }
        assertEquals(1, engine.listGroups(upa).size());
        assertEquals(2, engine.listGroups(upb).size());
        GroupPrincipal gp = engine.listGroups(upa).iterator().next();
        engine.deleteGroupRole("g", "role2");
        assertEquals(1, engine.listRoles(gp).size());
        assertEquals("role3", engine.listRoles(gp).iterator().next().getName());
        // check that the user roles are reported correctly
        assertEquals("role2 should still be there as it was added to the user directly too", 3, engine.listRoles(upa).size());
        boolean foundR1_5 = false;
        boolean foundR2_5 = false;
        boolean foundR3_5 = false;
        for (RolePrincipal rp : engine.listRoles(upa)) {
            if ("role1".equals(rp.getName())) {
                foundR1_5 = true;
            } else if ("role2".equals(rp.getName())) {
                foundR2_5 = true;
            } else if ("role3".equals(rp.getName())) {
                foundR3_5 = true;
            }
        }
        assertTrue(foundR1_5);
        assertTrue(foundR2_5);
        assertTrue(foundR3_5);
        assertEquals(2, engine.listRoles(upb).size());
        boolean foundR3_6 = false;
        boolean foundR4_6 = false;
        for (RolePrincipal rp : engine.listRoles(upb)) {
            if ("role3".equals(rp.getName())) {
                foundR3_6 = true;
            } else if ("role4".equals(rp.getName())) {
                foundR4_6 = true;
            }
        }
        assertTrue(foundR3_6);
        assertTrue(foundR4_6);
        engine.deleteGroup("b", "g");
        engine.deleteGroup("b", "g2");
        assertEquals(0, engine.listRoles(upb).size());
        engine.deleteUser("b");
        engine.deleteUser("a");
        assertEquals("Properties should be empty now", 0, p.size());
    } finally {
        if (!f.delete()) {
            fail("Could not delete temporary file: " + f);
        }
    }
}
Also used : GroupPrincipal(org.apache.karaf.jaas.boot.principal.GroupPrincipal) Properties(org.apache.felix.utils.properties.Properties) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) File(java.io.File) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal)

Example 18 with UserPrincipal

use of org.apache.karaf.jaas.boot.principal.UserPrincipal in project karaf by apache.

the class PropertiesLoginModuleTest method testLoginWithGroups.

@Test
public void testLoginWithGroups() throws Exception {
    File f = File.createTempFile(getClass().getName(), ".tmp");
    try {
        Properties p = new Properties(f);
        PropertiesBackingEngine pbe = new PropertiesBackingEngine(p);
        pbe.addUser("abc", "xyz");
        pbe.addRole("abc", "myrole");
        pbe.addUser("pqr", "abc");
        pbe.addGroup("pqr", "group1");
        pbe.addGroupRole("group1", "r1");
        PropertiesLoginModule module = new PropertiesLoginModule();
        Map<String, String> options = new HashMap<>();
        options.put(PropertiesLoginModule.USER_FILE, f.getAbsolutePath());
        Subject subject = new Subject();
        module.initialize(subject, new NamePasswordCallbackHandler("pqr", "abc"), null, options);
        Assert.assertEquals("Precondition", 0, subject.getPrincipals().size());
        Assert.assertTrue(module.login());
        Assert.assertTrue(module.commit());
        Assert.assertEquals(3, subject.getPrincipals().size());
        boolean foundUser = false;
        boolean foundRole = false;
        boolean foundGroup = false;
        for (Principal pr : subject.getPrincipals()) {
            if (pr instanceof UserPrincipal) {
                Assert.assertEquals("pqr", pr.getName());
                foundUser = true;
            } else if (pr instanceof GroupPrincipal) {
                Assert.assertEquals("group1", pr.getName());
                foundGroup = true;
            } else if (pr instanceof RolePrincipal) {
                Assert.assertEquals("r1", pr.getName());
                foundRole = true;
            }
        }
        Assert.assertTrue(foundUser);
        Assert.assertTrue(foundGroup);
        Assert.assertTrue(foundRole);
    } finally {
        if (!f.delete()) {
            Assert.fail("Could not delete temporary file: " + f);
        }
    }
}
Also used : HashMap(java.util.HashMap) Properties(org.apache.felix.utils.properties.Properties) Subject(javax.security.auth.Subject) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) NamePasswordCallbackHandler(org.apache.karaf.jaas.modules.NamePasswordCallbackHandler) GroupPrincipal(org.apache.karaf.jaas.boot.principal.GroupPrincipal) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) File(java.io.File) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Principal(java.security.Principal) GroupPrincipal(org.apache.karaf.jaas.boot.principal.GroupPrincipal) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) Test(org.junit.Test)

Example 19 with UserPrincipal

use of org.apache.karaf.jaas.boot.principal.UserPrincipal in project ddf by codice.

the class SslLdapLoginModule method doLogin.

protected boolean doLogin() throws LoginException {
    //--------- EXTRACT USERNAME AND PASSWORD FOR LDAP LOOKUP -------------
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);
    try {
        callbackHandler.handle(callbacks);
    } catch (IOException ioException) {
        throw new LoginException(ioException.getMessage());
    } catch (UnsupportedCallbackException unsupportedCallbackException) {
        boolean result;
        throw new LoginException(unsupportedCallbackException.getMessage() + " not available to obtain information from user.");
    }
    user = ((NameCallback) callbacks[0]).getName();
    if (user == null) {
        return false;
    }
    user = user.trim();
    validateUsername(user);
    char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
    // this method.
    if ("none".equalsIgnoreCase(getBindMethod()) && (tmpPassword != null)) {
        LOGGER.debug("Changing from authentication = none to simple since user or password was specified.");
        // default to simple so that the provided user/password will get checked
        setBindMethod(DEFAULT_AUTHENTICATION);
    }
    if (tmpPassword == null) {
        tmpPassword = new char[0];
    }
    //---------------------------------------------------------------------
    // RESET OBJECT STATE AND DECLARE LOCAL VARS
    principals = new HashSet<>();
    Connection connection;
    String userDn;
    //------------- CREATE CONNECTION #1 ----------------------------------
    try {
        connection = ldapConnectionFactory.getConnection();
    } catch (LdapException e) {
        LOGGER.info("Unable to get LDAP Connection from factory.", e);
        return false;
    }
    if (connection != null) {
        try {
            //------------- BIND #1 (CONNECTION USERNAME & PASSWORD) --------------
            try {
                BindRequest request;
                switch(getBindMethod()) {
                    case "Simple":
                        request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword);
                        break;
                    case "SASL":
                        request = Requests.newPlainSASLBindRequest(connectionUsername, connectionPassword);
                        break;
                    case "GSSAPI SASL":
                        request = Requests.newGSSAPISASLBindRequest(connectionUsername, connectionPassword);
                        ((GSSAPISASLBindRequest) request).setRealm(realm);
                        ((GSSAPISASLBindRequest) request).setKDCAddress(kdcAddress);
                        break;
                    case "Digest MD5 SASL":
                        request = Requests.newDigestMD5SASLBindRequest(connectionUsername, connectionPassword);
                        ((DigestMD5SASLBindRequest) request).setCipher(DigestMD5SASLBindRequest.CIPHER_HIGH);
                        ((DigestMD5SASLBindRequest) request).getQOPs().clear();
                        ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_CONF);
                        ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_INT);
                        ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH);
                        if (StringUtils.isNotEmpty(realm)) {
                            ((DigestMD5SASLBindRequest) request).setRealm(realm);
                        }
                        break;
                    default:
                        request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword);
                        break;
                }
                BindResult bindResult = connection.bind(request);
                if (!bindResult.isSuccess()) {
                    LOGGER.debug("Bind failed");
                    return false;
                }
            } catch (LdapException e) {
                LOGGER.debug("Unable to bind to LDAP server.", e);
                return false;
            }
            //--------- SEARCH #1, FIND USER DISTINGUISHED NAME -----------
            SearchScope scope;
            if (userSearchSubtree) {
                scope = SearchScope.WHOLE_SUBTREE;
            } else {
                scope = SearchScope.SINGLE_LEVEL;
            }
            userFilter = userFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
            userFilter = userFilter.replace("\\", "\\\\");
            ConnectionEntryReader entryReader = connection.search(userBaseDN, scope, userFilter);
            try {
                if (!entryReader.hasNext()) {
                    LOGGER.info("User {} not found in LDAP.", user);
                    return false;
                }
                SearchResultEntry searchResultEntry = entryReader.readEntry();
                userDn = searchResultEntry.getName().toString();
            } catch (LdapException | SearchResultReferenceIOException e) {
                LOGGER.info("Unable to read contents of LDAP user search.", e);
                return false;
            }
        } finally {
            //------------ CLOSE CONNECTION -------------------------------
            connection.close();
        }
    } else {
        return false;
    }
    //------------- CREATE CONNECTION #2 ----------------------------------
    try {
        connection = ldapConnectionFactory.getConnection();
    } catch (LdapException e) {
        LOGGER.info("Unable to get LDAP Connection from factory.", e);
        return false;
    }
    if (connection != null) {
        // Validate user's credentials.
        try {
            BindResult bindResult = connection.bind(userDn, tmpPassword);
            if (!bindResult.isSuccess()) {
                LOGGER.info("Bind failed");
                return false;
            }
        } catch (Exception e) {
            LOGGER.info("Unable to bind user to LDAP server.", e);
            return false;
        } finally {
            //------------ CLOSE CONNECTION -------------------------------
            connection.close();
        }
        //---------- ADD USER AS PRINCIPAL --------------------------------
        principals.add(new UserPrincipal(user));
    } else {
        return false;
    }
    //-------------- CREATE CONNECTION #3 ---------------------------------
    try {
        connection = ldapConnectionFactory.getConnection();
    } catch (LdapException e) {
        LOGGER.info("Unable to get LDAP Connection from factory.", e);
        return false;
    }
    if (connection != null) {
        try {
            //----- BIND #3 (CONNECTION USERNAME & PASSWORD) --------------
            try {
                BindResult bindResult = connection.bind(connectionUsername, connectionPassword);
                if (!bindResult.isSuccess()) {
                    LOGGER.info("Bind failed");
                    return false;
                }
            } catch (LdapException e) {
                LOGGER.info("Unable to bind to LDAP server.", e);
                return false;
            }
            //--------- SEARCH #3, GET ROLES ------------------------------
            SearchScope scope;
            if (roleSearchSubtree) {
                scope = SearchScope.WHOLE_SUBTREE;
            } else {
                scope = SearchScope.SINGLE_LEVEL;
            }
            roleFilter = roleFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
            roleFilter = roleFilter.replaceAll(Pattern.quote("%dn"), Matcher.quoteReplacement(userBaseDN));
            roleFilter = roleFilter.replaceAll(Pattern.quote("%fqdn"), Matcher.quoteReplacement(userDn));
            roleFilter = roleFilter.replace("\\", "\\\\");
            ConnectionEntryReader entryReader = connection.search(roleBaseDN, scope, roleFilter, roleNameAttribute);
            SearchResultEntry entry;
            //------------- ADD ROLES AS NEW PRINCIPALS -------------------
            try {
                while (entryReader.hasNext()) {
                    entry = entryReader.readEntry();
                    Attribute attr = entry.getAttribute(roleNameAttribute);
                    for (ByteString role : attr) {
                        principals.add(new RolePrincipal(role.toString()));
                    }
                }
            } catch (Exception e) {
                boolean result;
                throw new LoginException("Can't get user " + user + " roles: " + e.getMessage());
            }
        } finally {
            //------------ CLOSE CONNECTION -------------------------------
            connection.close();
        }
    } else {
        return false;
    }
    return true;
}
Also used : Attribute(org.forgerock.opendj.ldap.Attribute) ByteString(org.forgerock.opendj.ldap.ByteString) DigestMD5SASLBindRequest(org.forgerock.opendj.ldap.requests.DigestMD5SASLBindRequest) GSSAPISASLBindRequest(org.forgerock.opendj.ldap.requests.GSSAPISASLBindRequest) BindRequest(org.forgerock.opendj.ldap.requests.BindRequest) ByteString(org.forgerock.opendj.ldap.ByteString) GSSAPISASLBindRequest(org.forgerock.opendj.ldap.requests.GSSAPISASLBindRequest) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) LdapException(org.forgerock.opendj.ldap.LdapException) Connection(org.forgerock.opendj.ldap.Connection) IOException(java.io.IOException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) LdapException(org.forgerock.opendj.ldap.LdapException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) DigestMD5SASLBindRequest(org.forgerock.opendj.ldap.requests.DigestMD5SASLBindRequest) SearchScope(org.forgerock.opendj.ldap.SearchScope) LoginException(javax.security.auth.login.LoginException) BindResult(org.forgerock.opendj.ldap.responses.BindResult) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 20 with UserPrincipal

use of org.apache.karaf.jaas.boot.principal.UserPrincipal in project karaf by apache.

the class LDAPLoginModule method doLogin.

protected boolean doLogin() throws LoginException {
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);
    try {
        callbackHandler.handle(callbacks);
    } catch (IOException ioException) {
        throw new LoginException(ioException.getMessage());
    } catch (UnsupportedCallbackException unsupportedCallbackException) {
        throw new LoginException(unsupportedCallbackException.getMessage() + " not available to obtain information from user.");
    }
    user = doRFC2254Encoding(((NameCallback) callbacks[0]).getName());
    char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
    // If either a username or password is specified don't allow authentication = "none".
    // This is to prevent someone from logging into Karaf as any user without providing a 
    // valid password (because if authentication = none, the password could be any 
    // value - it is ignored).
    LDAPOptions options = new LDAPOptions(this.options);
    if (options.isUsernameTrim()) {
        if (user != null) {
            user = user.trim();
        }
    }
    String authentication = options.getAuthentication();
    if ("none".equals(authentication) && (user != null || tmpPassword != null)) {
        logger.debug("Changing from authentication = none to simple since user or password was specified.");
        // default to simple so that the provided user/password will get checked
        authentication = "simple";
        Map<String, Object> opts = new HashMap<>(this.options);
        opts.put(LDAPOptions.AUTHENTICATION, authentication);
        options = new LDAPOptions(opts);
    }
    boolean allowEmptyPasswords = options.getAllowEmptyPasswords();
    if (!"none".equals(authentication) && !allowEmptyPasswords && (tmpPassword == null || tmpPassword.length == 0)) {
        throw new LoginException("Empty passwords not allowed");
    }
    if (tmpPassword == null) {
        tmpPassword = new char[0];
    }
    String password = new String(tmpPassword);
    principals = new HashSet<>();
    LDAPCache cache = LDAPCache.getCache(options);
    // step 1: get the user DN
    final String[] userDnAndNamespace;
    try {
        logger.debug("Get the user DN.");
        userDnAndNamespace = cache.getUserDnAndNamespace(user);
        if (userDnAndNamespace == null) {
            return false;
        }
    } catch (Exception e) {
        logger.warn("Can't connect to the LDAP server: {}", e.getMessage(), e);
        throw new LoginException("Can't connect to the LDAP server: " + e.getMessage());
    }
    // step 2: bind the user using the DN
    DirContext context = null;
    try {
        // switch the credentials to the Karaf login user so that we can verify his password is correct
        logger.debug("Bind user (authentication).");
        Hashtable<String, Object> env = options.getEnv();
        env.put(Context.SECURITY_AUTHENTICATION, authentication);
        logger.debug("Set the security principal for " + userDnAndNamespace[0] + "," + options.getUserBaseDn());
        env.put(Context.SECURITY_PRINCIPAL, userDnAndNamespace[0] + "," + options.getUserBaseDn());
        env.put(Context.SECURITY_CREDENTIALS, password);
        logger.debug("Binding the user.");
        context = new InitialDirContext(env);
        logger.debug("User " + user + " successfully bound.");
        context.close();
    } catch (Exception e) {
        logger.warn("User " + user + " authentication failed.", e);
        throw new LoginException("Authentication failed: " + e.getMessage());
    } finally {
        if (context != null) {
            try {
                context.close();
            } catch (Exception e) {
            // ignore
            }
        }
    }
    principals.add(new UserPrincipal(user));
    // step 3: retrieving user roles
    try {
        String[] roles = cache.getUserRoles(user, userDnAndNamespace[0], userDnAndNamespace[1]);
        for (String role : roles) {
            principals.add(new RolePrincipal(role));
        }
    } catch (Exception e) {
        throw new LoginException("Can't get user " + user + " roles: " + e.getMessage());
    }
    return true;
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) IOException(java.io.IOException) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal)

Aggregations

UserPrincipal (org.apache.karaf.jaas.boot.principal.UserPrincipal)34 RolePrincipal (org.apache.karaf.jaas.boot.principal.RolePrincipal)26 Properties (org.apache.felix.utils.properties.Properties)16 Test (org.junit.Test)15 Subject (javax.security.auth.Subject)14 Principal (java.security.Principal)13 NamePasswordCallbackHandler (org.apache.karaf.jaas.modules.NamePasswordCallbackHandler)13 GroupPrincipal (org.apache.karaf.jaas.boot.principal.GroupPrincipal)12 IOException (java.io.IOException)9 LoginException (javax.security.auth.login.LoginException)9 ArrayList (java.util.ArrayList)8 NameCallback (javax.security.auth.callback.NameCallback)7 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)7 File (java.io.File)6 Callback (javax.security.auth.callback.Callback)6 HashMap (java.util.HashMap)5 PasswordCallback (javax.security.auth.callback.PasswordCallback)5 FailedLoginException (javax.security.auth.login.FailedLoginException)4 DirContext (javax.naming.directory.DirContext)3 CallbackHandler (javax.security.auth.callback.CallbackHandler)2