Example usage for javax.security.auth.callback UnsupportedCallbackException getMessage

List of usage examples for javax.security.auth.callback UnsupportedCallbackException getMessage

Introduction

In this page you can find the example usage for javax.security.auth.callback UnsupportedCallbackException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:info.magnolia.jaas.sp.jcr.JCRAuthenticationModule.java

/**
 * Authenticate against magnolia/jcr user repository
 *//*w w w .  j a v a2  s.  c  om*/
public boolean login() throws LoginException {
    if (this.callbackHandler == null) {
        throw new LoginException("Error: no CallbackHandler available for JCRModule");
    }

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("name");
    callbacks[1] = new PasswordCallback("pswd", false);

    this.success = false;
    try {
        this.callbackHandler.handle(callbacks);
        this.name = ((NameCallback) callbacks[0]).getName();
        this.pswd = ((PasswordCallback) callbacks[1]).getPassword();
        this.success = this.isValidUser();
    } catch (IOException ioe) {
        if (log.isDebugEnabled()) {
            log.debug("Exception caught", ioe);
        }
        throw new LoginException(ioe.toString());
    } catch (UnsupportedCallbackException ce) {
        if (log.isDebugEnabled()) {
            log.debug(ce.getMessage(), ce);
        }
        throw new LoginException(ce.getCallback().toString() + " not available");
    }
    if (!this.success) {
        throw new LoginException("failed to authenticate " + this.name);
    }

    return this.success;
}

From source file:com.cubusmail.server.mail.security.MailboxLoginModule.java

public boolean login() throws LoginException {

    if (this.callbackHandler == null) {
        log.fatal("callbackHandler is null");
        throw new LoginException(IErrorCodes.EXCEPTION_AUTHENTICATION_FAILED);
    }/*www.  jav  a  2  s  .  c om*/

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username");
    callbacks[1] = new PasswordCallback("Password", false);

    try {
        this.callbackHandler.handle(callbacks);
        String username = ((NameCallback) callbacks[0]).getName();

        char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
        if (tmpPassword == null) {
            // treat a NULL password as an empty password
            tmpPassword = new char[0];
        }
        char[] password = new char[tmpPassword.length];
        System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length);
        ((PasswordCallback) callbacks[1]).clearPassword();

        // start authentication
        // TODO: very dirty, must be replaced by Spring Security stuff
        ApplicationContext context = WebApplicationContextUtils
                .getRequiredWebApplicationContext(SessionManager.getRequest().getSession().getServletContext());
        MailboxFactory factory = context.getBean(MailboxFactory.class);
        IMailbox mailbox = factory.createMailbox(IMailbox.TYPE_IMAP);
        mailbox.init(username, new String(password));

        log.debug("Start login...");
        mailbox.login();
        log.debug("Login successful");

        this.mailboxPrincipal = new MailboxPrincipal(username, mailbox);
        this.succeeded = true;
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        throw new LoginException(ioe.toString());
    } catch (UnsupportedCallbackException uce) {
        log.error(uce.getMessage(), uce);
        throw new LoginException(IErrorCodes.EXCEPTION_AUTHENTICATION_FAILED);
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        mapMessagingException(e);
    }

    return this.succeeded;
}

From source file:info.magnolia.jaas.sp.AbstractLoginModule.java

@Override
public boolean login() throws LoginException {
    if (this.getSkip()) {
        return true;
    }// w  w  w  .jav  a2s  . c  om

    if (this.callbackHandler == null) {
        throw new LoginException("Error: no CallbackHandler available");
    }

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("name");
    callbacks[1] = new PasswordCallback("pswd", false);

    // if the realm is not defined in the jaas configuration
    // we ask use a callback to get the value
    if (this.useRealmCallback) {
        callbacks = (Callback[]) ArrayUtils.add(callbacks, new RealmCallback());
    }

    this.success = false;
    try {
        this.callbackHandler.handle(callbacks);
        this.name = ((NameCallback) callbacks[0]).getName();
        this.pswd = ((PasswordCallback) callbacks[1]).getPassword();
        if (this.useRealmCallback) {
            String aRealm = ((RealmCallback) callbacks[2]).getRealm();
            this.realm = StringUtils.isBlank(aRealm) ? this.realm : Realm.Factory.newRealm(aRealm);
        }

        this.validateUser();
    } catch (IOException ioe) {
        log.debug("Exception caught", ioe);
        throw new LoginException(ioe.toString());
    } catch (UnsupportedCallbackException ce) {
        log.debug(ce.getMessage(), ce);
        throw new LoginException(ce.getCallback().toString() + " not available");
    }

    // TODO: should not we set success BEFORE calling validateUser to give it chance to decide whether to throw an exception or reset the value to false?
    this.success = true;
    this.setSharedStatus(STATUS_SUCCEEDED);
    return this.success;
}

From source file:ddf.ldap.ldaplogin.SslLdapLoginModule.java

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 {/* w  ww. ja v a  2s  .co m*/
        callbackHandler.handle(callbacks);
    } catch (IOException ioException) {
        LOGGER.debug("Exception while handling login.", ioException);
        throw new LoginException(ioException.getMessage());
    } catch (UnsupportedCallbackException unsupportedCallbackException) {
        LOGGER.debug("Exception while handling login.", unsupportedCallbackException);
        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();

    // 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).
    // Username is not checked in this conditional because a null username immediately exits
    // 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 = ldapConnectionPool.borrowObject();
    } catch (Exception e) {
        LOGGER.info("Unable to obtain ldap connection from pool", e);
        return false;
    }
    try {

        if (connection != null) {
            // ------------- BIND #1 (CONNECTION USERNAME & PASSWORD) --------------
            try {
                BindRequest request;
                switch (bindMethod) {
                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;
                }
                LOGGER.trace("Attempting LDAP bind for administrator: {}", connectionUsername);
                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;
            }
            LOGGER.trace("LDAP bind successful for administrator: {}", connectionUsername);
            // --------- SEARCH #1, FIND USER DISTINGUISHED NAME -----------
            SearchScope scope;
            scope = userSearchSubtree ? SearchScope.WHOLE_SUBTREE : SearchScope.SINGLE_LEVEL;
            userFilter = userFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
            userFilter = userFilter.replace("\\", "\\\\");
            LOGGER.trace("Performing LDAP query for user: {} at {} with filter {}", user, userBaseDN,
                    userFilter);
            try (ConnectionEntryReader entryReader = connection.search(userBaseDN, scope, userFilter)) {
                while (entryReader.hasNext() && entryReader.isReference()) {
                    LOGGER.debug("Referral ignored while searching for user {}", user);
                    entryReader.readReference();
                }
                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;
            }

            // ----- BIND #2 (USER DISTINGUISHED NAME AND PASSWORD) ------------
            // Validate user's credentials.
            try {
                LOGGER.trace("Attempting LDAP bind for user: {}", userDn);
                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.", userDn, e);
                return false;
            }

            LOGGER.trace("LDAP bind successful for user: {}", userDn);

            // ---------- ADD USER AS PRINCIPAL --------------------------------
            principals.add(new UserPrincipal(user));

            // ----- BIND #3 (CONNECTION USERNAME & PASSWORD) --------------
            try {
                LOGGER.trace("Attempting LDAP bind for administrator: {}", connectionUsername);
                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;
            }
            LOGGER.trace("LDAP bind successful for administrator: {}", connectionUsername);

            // --------- SEARCH #3, GET ROLES ------------------------------
            scope = roleSearchSubtree ? SearchScope.WHOLE_SUBTREE : 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("\\", "\\\\");
            LOGGER.trace(
                    "Performing LDAP query for roles for user: {} at {} with filter {} for role attribute {}",
                    user, roleBaseDN, roleFilter, roleNameAttribute);

            // ------------- ADD ROLES AS NEW PRINCIPALS -------------------
            try (ConnectionEntryReader entryReader = connection.search(roleBaseDN, scope, roleFilter,
                    roleNameAttribute)) {
                SearchResultEntry entry;
                while (entryReader.hasNext()) {
                    if (entryReader.isEntry()) {
                        entry = entryReader.readEntry();
                        Attribute attr = entry.getAttribute(roleNameAttribute);
                        if (attr == null) {
                            throw new LoginException("No attributes returned for [" + roleNameAttribute + " : "
                                    + roleBaseDN + "]");
                        }
                        for (ByteString role : attr) {
                            principals.add(new RolePrincipal(role.toString()));
                        }
                    } else {
                        // Got a continuation reference.
                        final SearchResultReference ref = entryReader.readReference();
                        LOGGER.debug("Skipping result reference: {}", ref.getURIs());
                    }
                }
            } catch (Exception e) {
                LOGGER.debug("Exception while getting roles for [" + user + "].", e);
                throw new LoginException("Can't get roles for [" + user + "]: " + e.getMessage());
            }
        } else {
            LOGGER.trace("LDAP Connection was null could not authenticate user.");
            return false;
        }

        return true;
    } finally {
        ldapConnectionPool.returnObject(connection);
    }
}

From source file:org.apache.felix.karaf.jaas.modules.properties.PropertiesLoginModule.java

public boolean login() throws LoginException {
    Properties users = new Properties();
    File f = new File(usersFile);
    try {//from   w  w  w  . j av  a 2 s .  c  o m
        users.load(new java.io.FileInputStream(f));
    } catch (IOException ioe) {
        throw new LoginException("Unable to load user properties file " + f);
    }

    Callback[] callbacks = new Callback[2];

    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);
    try {
        callbackHandler.handle(callbacks);
    } catch (IOException ioe) {
        throw new LoginException(ioe.getMessage());
    } catch (UnsupportedCallbackException uce) {
        throw new LoginException(uce.getMessage() + " not available to obtain information from user");
    }
    user = ((NameCallback) callbacks[0]).getName();
    char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
    if (tmpPassword == null) {
        tmpPassword = new char[0];
    }

    String userInfos = (String) users.get(user);
    if (userInfos == null) {
        throw new FailedLoginException("User does not exist");
    }
    String[] infos = userInfos.split(",");
    if (!new String(tmpPassword).equals(infos[0])) {
        throw new FailedLoginException("Password does not match");
    }

    principals = new HashSet<Principal>();
    principals.add(new UserPrincipal(user));
    for (int i = 1; i < infos.length; i++) {
        principals.add(new RolePrincipal(infos[i]));
    }

    users.clear();

    if (debug) {
        LOG.debug("login " + user);
    }
    return true;
}

From source file:org.apache.jackrabbit.core.security.authentication.AbstractLoginModule.java

/**
 * Method tries to acquire an Impersonator in the follwing order:
 * <ul>// ww  w  .  ja v a  2  s . com
 * <li> Try to access it from the {@link Credentials} via {@link SimpleCredentials#getAttribute(String)}</li>
 * <li> Ask CallbackHandler for Impersonator with use of {@link ImpersonationCallback}.</li>
 * </ul>
 *
 * @param credentials which, may contain an impersonation Subject
 * @return impersonation subject or null if non contained
 * @see #login()
 * @see #impersonate(java.security.Principal, javax.jcr.Credentials)
 */
protected Subject getImpersonatorSubject(Credentials credentials) {
    Subject impersonator = null;
    if (credentials == null) {
        try {
            ImpersonationCallback impers = new ImpersonationCallback();
            callbackHandler.handle(new Callback[] { impers });
            impersonator = impers.getImpersonator();
        } catch (UnsupportedCallbackException e) {
            log.warn(e.getCallback().getClass().getName() + " not supported: Unable to perform Impersonation.");
        } catch (IOException e) {
            log.error(
                    "Impersonation-Callback failed: " + e.getMessage() + ": Unable to perform Impersonation.");
        }
    } else if (credentials instanceof SimpleCredentials) {
        SimpleCredentials sc = (SimpleCredentials) credentials;
        impersonator = (Subject) sc.getAttribute(SecurityConstants.IMPERSONATOR_ATTRIBUTE);
    }
    return impersonator;
}

From source file:org.apache.jackrabbit.core.security.authentication.AbstractLoginModule.java

/**
 * Method tries to resolve the {@link Credentials} used for login. It takes
 * authentication-extension of an already authenticated {@link Subject} into
 * accout./*ww  w . j av  a 2  s  .  c o m*/
 * <p/>
 * Therefore the credentials are searchred as follows:
 * <ol>
 * <li>Test if the shared state contains credentials.</li>
 * <li>Ask CallbackHandler for Credentials with using a {@link
 * CredentialsCallback}. Expects {@link CredentialsCallback#getCredentials}
 * to return an instance of {@link Credentials}.</li>
 * <li>Ask the Subject for its public <code>SimpleCredentials</code> see
 * {@link Subject#getPublicCredentials(Class)}, thus enabling to
 * preauthenticate the Subject.</li>
 * </ol>
 *
 * @return Credentials or null if not found
 * @see #login()
 */
protected Credentials getCredentials() {
    Credentials credentials = null;
    if (sharedState.containsKey(KEY_CREDENTIALS)) {
        credentials = (Credentials) sharedState.get(KEY_CREDENTIALS);
    } else {
        try {
            CredentialsCallback callback = new CredentialsCallback();
            callbackHandler.handle(new Callback[] { callback });
            Credentials creds = callback.getCredentials();
            if (null != creds) {
                if (creds instanceof SimpleCredentials) {
                    credentials = creds;
                } else if (creds instanceof GuestCredentials) {
                    credentials = creds;
                }
                sharedState.put(KEY_CREDENTIALS, credentials);
            }
        } catch (UnsupportedCallbackException e) {
            log.warn("Credentials-Callback not supported try Name-Callback");
        } catch (IOException e) {
            log.error("Credentials-Callback failed: " + e.getMessage() + ": try Name-Callback");
        }
    }
    // ask subject if still no credentials
    if (null == credentials) {
        // try if subject contains SimpleCredentials
        Set preAuthCreds = subject.getPublicCredentials(SimpleCredentials.class);
        if (!preAuthCreds.isEmpty()) {
            credentials = (Credentials) preAuthCreds.iterator().next();
        }
    }
    return credentials;
}

From source file:org.apache.jackrabbit.core.security.authentication.AbstractLoginModule.java

/**
 * Method supports tries to acquire a UserID in the follwing order:
 * <ol>/*  w  w  w . j  ava2s .  c  om*/
 * <li>If passed credentials are {@link GuestCredentials} the anonymous user id
 * is returned.</li>
 * <li>Try to access it from the {@link Credentials} via {@link
 * SimpleCredentials#getUserID()}</li>
 * <li>Ask CallbackHandler for User-ID with use of {@link NameCallback}.</li>
 * <li>Test if the 'sharedState' contains a login name.</li>
 * <li>Fallback: return the anonymous UserID.</li>
 * </ol>
 *
 * @param credentials which, may contain a User-ID
 * @return The userId retrieved from the credentials or by any other means
 * described above.
 * @see #login()
 */
protected String getUserID(Credentials credentials) {
    String userId = null;
    if (credentials != null) {
        if (credentials instanceof GuestCredentials) {
            userId = anonymousId;
        } else if (credentials instanceof SimpleCredentials) {
            userId = ((SimpleCredentials) credentials).getUserID();
        } else {
            try {
                NameCallback callback = new NameCallback("User-ID: ");
                callbackHandler.handle(new Callback[] { callback });
                userId = callback.getName();
            } catch (UnsupportedCallbackException e) {
                log.warn("Credentials- or NameCallback must be supported");
            } catch (IOException e) {
                log.error("Name-Callback failed: " + e.getMessage());
            }
        }
    }
    if (userId == null && sharedState.containsKey(KEY_LOGIN_NAME)) {
        userId = (String) sharedState.get(KEY_LOGIN_NAME);
    }

    // still no userId -> anonymousID if its has been defined.
    // TODO: check again if correct when used with 'extendedAuth'
    if (userId == null) {
        userId = anonymousId;
    }
    return userId;
}

From source file:org.apache.jackrabbit.core.security.JahiaLoginModule.java

@Override
public boolean login() throws LoginException {
    try {/*from   w ww  .  ja va2 s  .  c o m*/
        String name = null;
        char[] pass = null;
        String realm = null;
        String impersonatorName = null;
        char[] impersonatorPass = null;
        Callback[] callbacks = new Callback[] { new CredentialsCallback() };
        callbackHandler.handle(callbacks);
        Credentials credentials = ((CredentialsCallback) callbacks[0]).getCredentials();

        if (credentials instanceof SimpleCredentials) {
            SimpleCredentials simpleCredentials = (SimpleCredentials) credentials;
            name = simpleCredentials.getUserID();
            pass = simpleCredentials.getPassword();
            realm = (String) simpleCredentials.getAttribute(REALM_ATTRIBUTE);

            SimpleCredentials impersonatorCredentials = (SimpleCredentials) simpleCredentials
                    .getAttribute(SecurityConstants.IMPERSONATOR_ATTRIBUTE);
            if (impersonatorCredentials != null) {
                // there were impersonator credentials supplied -> will use them
                impersonatorName = impersonatorCredentials.getUserID();
                impersonatorPass = impersonatorCredentials.getPassword();
            }
        } else {
            callbacks = new Callback[] { new NameCallback("name?"), new PasswordCallback("pass?", false) };
            callbackHandler.handle(callbacks);

            name = ((NameCallback) callbacks[0]).getName();
            pass = ((PasswordCallback) callbacks[1]).getPassword();
        }
        if (name != null) {
            if (SYSTEM.equals(name)) {
                String key = new String(pass);
                Token token = removeToken(name, key);
                if (token != null) {
                    principals.add(new JahiaPrincipal(SYSTEM, realm, true, false));
                    principals.add(new SystemPrincipal());
                }
            } else if (name.startsWith(SYSTEM)) {
                String key = new String(pass);
                Token token = removeToken(name, key);
                if (token != null) {
                    principals.add(new JahiaPrincipal(name.substring(SYSTEM.length()), realm, true, false));
                    principals.add(new SystemPrincipal());
                }
            } else if (GUEST.equals(name)) {
                principals.add(new JahiaPrincipal(GUEST, null, false, true));
                principals.add(new AnonymousPrincipal());
            } else {
                String key = new String(impersonatorPass != null ? impersonatorPass : pass);
                String lookupUser = impersonatorName != null ? impersonatorName : name;
                Token token = removeToken(lookupUser, key);

                boolean ok = token != null;
                JCRUserNode user = null;
                if (!ok) {
                    user = JahiaUserManagerService.getInstance().lookupUser(lookupUser);
                    ok = user != null && user.verifyPassword(key);
                }
                if (ok && impersonatorName != null) {
                    // ensure the impersonator is root
                    if (user == null) {
                        user = JahiaUserManagerService.getInstance().lookupUser(lookupUser);
                    }
                    if (user == null || !user.isRoot()) {
                        throw new FailedLoginException(
                                "Only root user credentials can be used as an impersonator.");
                    }
                    // ensure the user exists
                    if (!JahiaUserManagerService.getInstance().userExists(name)) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("User {} is not known, a the guest will be used instead", name,
                                    impersonatorName);
                        }
                        principals.add(new JahiaPrincipal(GUEST, null, false, true));
                        ok = false;
                    }
                }

                if (ok) {
                    principals.add(new JahiaPrincipal(name, realm, false, false));
                    if (realm == null) {
                        if (JahiaGroupManagerService.getInstance().isAdminMember(name, null, null)) {
                            principals.add(new AdminPrincipal(name));
                        }
                    }
                }
            }
            if (principals.isEmpty()) {
                throw new FailedLoginException();
            }
        }
    } catch (UnsupportedCallbackException e) {
        // ignore
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return !principals.isEmpty();
}

From source file:org.apache.karaf.jaas.modules.properties.DigestPasswordLoginModule.java

public boolean login() throws LoginException {
    if (usersFile == null) {
        throw new LoginException("The property users may not be null");
    }//from  w  w w.  ja  v  a2  s  .co m
    File f = new File(usersFile);
    if (!f.exists()) {
        throw new LoginException("Users file not found at " + f);
    }

    Properties users;
    try {
        users = new Properties(f);
    } catch (IOException ioe) {
        throw new LoginException("Unable to load user properties file " + f);
    }

    Callback[] callbacks = new Callback[2];

    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);
    if (callbackHandler != null) {
        try {
            callbackHandler.handle(callbacks);
        } catch (IOException ioe) {
            throw new LoginException(ioe.getMessage());
        } catch (UnsupportedCallbackException uce) {
            throw new LoginException(uce.getMessage() + " not available to obtain information from user");
        }
    }
    // user callback get value
    if (((NameCallback) callbacks[0]).getName() == null) {
        throw new LoginException("Username can not be null");
    }
    user = ((NameCallback) callbacks[0]).getName();
    if (user.startsWith(PropertiesBackingEngine.GROUP_PREFIX)) {
        // you can't log in under a group name
        throw new FailedLoginException("login failed");
    }

    // password callback get value
    if (((PasswordCallback) callbacks[1]).getPassword() == null) {
        throw new LoginException("Password can not be null");
    }
    String password = new String(((PasswordCallback) callbacks[1]).getPassword());

    // user infos container read from the users properties file
    String userInfos = null;
    try {
        userInfos = (String) users.get(user);
    } catch (NullPointerException e) {
        //error handled in the next statement
    }
    if (userInfos == null) {
        if (!this.detailedLoginExcepion) {
            throw new FailedLoginException("login failed");
        } else {
            throw new FailedLoginException("User " + user + " does not exist");
        }
    }

    // the password is in the first position
    String[] infos = userInfos.split(",");
    String storedPassword = infos[0];

    CallbackHandler myCallbackHandler = null;

    try {
        Field field = callbackHandler.getClass().getDeclaredField("ch");
        field.setAccessible(true);
        myCallbackHandler = (CallbackHandler) field.get(callbackHandler);
    } catch (Exception e) {
        throw new LoginException("Unable to load underlying callback handler");
    }

    if (myCallbackHandler instanceof NameDigestPasswordCallbackHandler) {
        NameDigestPasswordCallbackHandler digestCallbackHandler = (NameDigestPasswordCallbackHandler) myCallbackHandler;
        storedPassword = doPasswordDigest(digestCallbackHandler.getNonce(),
                digestCallbackHandler.getCreatedTime(), storedPassword);
    }

    // check the provided password
    if (!checkPassword(password, storedPassword)) {
        if (!this.detailedLoginExcepion) {
            throw new FailedLoginException("login failed");
        } else {
            throw new FailedLoginException("Password for " + user + " does not match");
        }
    }

    principals = new HashSet<Principal>();
    principals.add(new UserPrincipal(user));
    for (int i = 1; i < infos.length; i++) {
        if (infos[i].trim().startsWith(PropertiesBackingEngine.GROUP_PREFIX)) {
            // it's a group reference
            principals.add(new GroupPrincipal(
                    infos[i].trim().substring(PropertiesBackingEngine.GROUP_PREFIX.length())));
            String groupInfo = (String) users.get(infos[i].trim());
            if (groupInfo != null) {
                String[] roles = groupInfo.split(",");
                for (int j = 1; j < roles.length; j++) {
                    principals.add(new RolePrincipal(roles[j].trim()));
                }
            }
        } else {
            // it's an user reference
            principals.add(new RolePrincipal(infos[i].trim()));
        }
    }

    users.clear();

    if (debug) {
        LOGGER.debug("Successfully logged in {}", user);
    }
    return true;
}