Example usage for javax.security.auth.login LoginException LoginException

List of usage examples for javax.security.auth.login LoginException LoginException

Introduction

In this page you can find the example usage for javax.security.auth.login LoginException LoginException.

Prototype

public LoginException(String msg) 

Source Link

Document

Constructs a LoginException with the specified detail message.

Usage

From source file:gov.nih.nci.security.authentication.loginmodules.CSMLoginModule.java

public boolean changePassword(String newPassword) throws LoginException, CSInternalLoginException,
        CSInternalConfigurationException, CSConfigurationException {
    if (callbackHandler == null) {
        if (log.isDebugEnabled())
            log.debug("Authentication|||login|Failure| Error in obtaining the CallBack Handler |");
        throw new LoginException("Error in obtaining Callback Handler");
    }//from w  w  w  .jav  a 2  s. c o m
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("userid: ");
    callbacks[1] = new PasswordCallback("password: ", false);

    try {
        callbackHandler.handle(callbacks);
        userID = ((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];
        }
        password = new char[tmpPassword.length];
        System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length);
        ((PasswordCallback) callbacks[1]).clearPassword();
    } catch (java.io.IOException e) {
        if (log.isDebugEnabled())
            log.debug("Authentication|||login|Failure| Error in creating the CallBack Handler |"
                    + e.getMessage());
        throw new LoginException("Error in Creating the CallBack Handler");
    } catch (UnsupportedCallbackException e) {
        if (log.isDebugEnabled())
            log.debug("Authentication|||login|Failure| Error in creating the CallBack Handler |"
                    + e.getMessage());
        throw new LoginException("Error in Creating the CallBack Handler");
    }

    try {
        //now validate user
        if (validate(options, userID, password, subject)) {
            DataConfiguration config = ConfigurationHelper.getConfiguration();
            String encryptedPassword = new String(password);
            encryptedPassword = StringUtilities.initTrimmedString(encryptPassword(encryptedPassword, "YES"));
            if (encryptedPassword.equals(encryptPassword(newPassword, "YES"))) {
                throw new LoginException("The password should be different from the previous passwords");
            }
            if (passwordMatchs(options, userID, newPassword,
                    Integer.parseInt(config.getString("PASSWORD_MATCH_NUM")))) {
                throw new LoginException("The password should be different from the previous passwords");
            } else {
                changePassword(options, userID, newPassword);
                if (isFirstTimeLogin(options, userID))
                    resetFirstTimeLogin(options, userID);

                insertIntoPasswordHistory(options, userID, password);
                updatePasswordExpiryDate(options, userID, DateUtils.addDays(Calendar.getInstance().getTime(),
                        Integer.parseInt(config.getString("PASSWORD_EXPIRY_DAYS"))));
            }
        } else {
            // clear the values         
            loginSuccessful = false;
            userID = null;
            password = null;

            throw new FailedLoginException("Invalid Login Credentials");
        }
    } catch (FailedLoginException fle) {
        if (log.isDebugEnabled())
            if (log.isDebugEnabled())
                log.debug("Authentication|||login|Failure| Invalid Login Credentials |" + fle.getMessage());
        throw new LoginException("Invalid Login Credentials");
    }
    if (log.isDebugEnabled())
        log.debug("Authentication|||login|Success| Authentication is " + loginSuccessful + "|");
    return loginSuccessful;
}

From source file:org.jasig.cas.client.jaas.CasLoginModule.java

public boolean commit() throws LoginException {
    if (this.assertion != null) {
        if (this.ticket != null) {
            this.subject.getPrivateCredentials().add(this.ticket);
        } else {//from w  w w .  j  a  v  a2s .  com
            throw new LoginException("Ticket credential not found.");
        }

        final AssertionPrincipal casPrincipal = new AssertionPrincipal(this.assertion.getPrincipal().getName(),
                this.assertion);
        this.subject.getPrincipals().add(casPrincipal);

        // Add group containing principal as sole member
        // Supports JBoss JAAS use case
        final Group principalGroup = new SimpleGroup(this.principalGroupName);
        principalGroup.addMember(casPrincipal);
        this.subject.getPrincipals().add(principalGroup);

        // Add group principal containing role data
        final Group roleGroup = new SimpleGroup(this.roleGroupName);
        for (int i = 0; i < defaultRoles.length; i++) {
            roleGroup.addMember(new SimplePrincipal(defaultRoles[i]));
        }
        final Map attributes = this.assertion.getPrincipal().getAttributes();
        final Iterator nameIterator = attributes.keySet().iterator();
        while (nameIterator.hasNext()) {
            final Object key = nameIterator.next();
            if (this.roleAttributeNames.contains(key)) {
                // Attribute value is Object if singular or Collection if plural
                final Object value = attributes.get(key);
                if (value instanceof Collection) {
                    final Iterator valueIterator = ((Collection) value).iterator();
                    while (valueIterator.hasNext()) {
                        roleGroup.addMember(new SimplePrincipal(valueIterator.next().toString()));
                    }
                } else {
                    roleGroup.addMember(new SimplePrincipal(value.toString()));
                }
            }
        }
        this.subject.getPrincipals().add(roleGroup);

        // Place principal name in shared state for downstream JAAS modules (module chaining use case)
        this.sharedState.put(LOGIN_NAME, casPrincipal.getName());

        if (log.isDebugEnabled()) {
            if (log.isDebugEnabled()) {
                log.debug("Created JAAS subject with principals: " + subject.getPrincipals());
            }
        }

        if (this.cacheAssertions) {
            if (log.isDebugEnabled()) {
                log.debug("Caching assertion for principal " + this.assertion.getPrincipal());
            }
            ASSERTION_CACHE.put(this.ticket, this.assertion);
        }
    } else {
        // Login must have failed if there is no assertion defined
        // Need to clean up state
        if (this.ticket != null) {
            this.ticket = null;
        }
    }
    return true;
}

From source file:org.collectionspace.authentication.realm.db.CSpaceDbRealm.java

private Connection getConnection() throws LoginException, SQLException {
    InitialContext ctx = null;/*from w w w  . j  a v a 2 s  .  com*/
    Connection conn = null;
    try {
        ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup(getDataSourceName());
        if (ds == null) {
            throw new IllegalArgumentException("datasource not found: " + getDataSourceName());
        }
        conn = ds.getConnection();
        return conn;
    } catch (NamingException ex) {
        LoginException le = new LoginException("Error looking up DataSource from: " + getDataSourceName());
        le.initCause(ex);
        throw le;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
            }
        }
    }

}

From source file:org.betaconceptframework.astroboa.engine.service.security.AstroboaLogin.java

/**
 * /*  w  ww . ja  v a2  s .  co m*/
 * TAKEN FROM Jboss class
 *  
 * org.jboss.security.auth.spi.UsernamePasswordLoginModule
 * 
 * and adjust it to Astroboa requirements
 * 
 * @return
 * @throws LoginException
 */
private String[] getAuthenticationInformation() throws LoginException {
    String[] info = { null, null, null, null, null };
    // prompt for a username and password
    if (callbackHandler == null) {
        throw new LoginException(
                "Error: no CallbackHandler available " + "to collect authentication information");
    }

    NameCallback nc = new NameCallback("User name: ", "guest");
    PasswordCallback pc = new PasswordCallback("Password: ", false);
    AstroboaAuthenticationCallback authenticationCallback = new AstroboaAuthenticationCallback(
            "Astroboa authentication info");

    Callback[] callbacks = { nc, pc, authenticationCallback };
    String username = null;
    String password = null;
    String identityStoreLocation = null;
    String userSecretKey = null;
    String repositoryId = null;

    try {
        callbackHandler.handle(callbacks);
        username = nc.getName();
        char[] tmpPassword = pc.getPassword();
        if (tmpPassword != null) {
            char[] credential = new char[tmpPassword.length];
            System.arraycopy(tmpPassword, 0, credential, 0, tmpPassword.length);
            pc.clearPassword();
            password = new String(credential);
        }

        identityStoreLocation = authenticationCallback.getIdentityStoreLocation();

        useExternalIdentity = authenticationCallback.isExternalIdentityStore();

        userSecretKey = authenticationCallback.getSecretKey();

        repositoryId = authenticationCallback.getRepositoryId();
    } catch (IOException e) {
        LoginException le = new LoginException("Failed to get username/password");
        le.initCause(e);
        throw le;
    } catch (UnsupportedCallbackException e) {
        LoginException le = new LoginException("CallbackHandler does not support: " + e.getCallback());
        le.initCause(e);
        throw le;
    }
    info[0] = username;
    info[1] = password;
    info[2] = userSecretKey;
    info[3] = identityStoreLocation;
    info[4] = repositoryId;

    return info;
}

From source file:edu.vt.middleware.ldap.jaas.AbstractLoginModule.java

/**
 * This attempts to retrieve credentials for the supplied name and password
 * callbacks. If useFirstPass or tryFirstPass is set, then name and password
 * data is retrieved from shared state. Otherwise a callback handler is used
 * to get the data. Set useCallback to force a callback handler to be used.
 *
 * @param  nameCb  to set name for/*from   w ww .j a v  a 2s .  com*/
 * @param  passCb  to set password for
 * @param  useCallback  whether to force a callback handler
 *
 * @throws  LoginException  if the callback handler fails
 */
protected void getCredentials(final NameCallback nameCb, final PasswordCallback passCb,
        final boolean useCallback) throws LoginException {
    if (this.logger.isTraceEnabled()) {
        this.logger.trace("Begin getCredentials");
        this.logger.trace("  useFistPass = " + this.useFirstPass);
        this.logger.trace("  tryFistPass = " + this.tryFirstPass);
        this.logger.trace("  useCallback = " + useCallback);
        this.logger.trace("  callbackhandler class = " + this.callbackHandler.getClass().getName());
        this.logger.trace("  name callback class = " + nameCb.getClass().getName());
        this.logger.trace("  password callback class = " + passCb.getClass().getName());
    }
    try {
        if ((this.useFirstPass || this.tryFirstPass) && !useCallback) {
            nameCb.setName((String) this.sharedState.get(LOGIN_NAME));
            passCb.setPassword((char[]) this.sharedState.get(LOGIN_PASSWORD));
        } else if (this.callbackHandler != null) {
            this.callbackHandler.handle(new Callback[] { nameCb, passCb });
        } else {
            throw new LoginException("No CallbackHandler available. "
                    + "Set useFirstPass, tryFirstPass, or provide a CallbackHandler");
        }
    } catch (IOException e) {
        if (this.logger.isErrorEnabled()) {
            this.logger.error("Error reading data from callback handler", e);
        }
        this.loginSuccess = false;
        throw new LoginException(e.getMessage());
    } catch (UnsupportedCallbackException e) {
        if (this.logger.isErrorEnabled()) {
            this.logger.error("Unsupported callback", e);
        }
        this.loginSuccess = false;
        throw new LoginException(e.getMessage());
    }
}

From source file:com.redhat.rhn.manager.user.UserManager.java

/**
 * Login the user with the given username and password.
 * @param username User's login name/*from  w ww  .  j a v  a2s  .c  om*/
 * @param password User's unencrypted password.
 * @return Returns the user if login is successful, or null othewise.
 * @throws LoginException if login fails.  The message is a string resource key.
 */
public static User loginUser(String username, String password) throws LoginException {
    try {
        User user = UserFactory.lookupByLogin(username);
        if (!user.authenticate(password)) {
            throw new LoginException("error.invalid_login");
        } else if (user.isDisabled()) {
            throw new LoginException("account.disabled");
        } else {
            user.setLastLoggedIn(new Date());
            // need to disable OAI_SYNC during login
            storeUser(user);
            return user;
        }
    } catch (LookupException le) {
        throw new LoginException("error.invalid_login");
    }
}

From source file:fr.paris.lutece.plugins.mylutece.authentication.MultiLuteceAuthentication.java

/**
 *
 * {@inheritDoc}/*from w  w w.  j ava2s  .c o  m*/
 */
public LuteceUser login(String strUserName, String strUserPassword, HttpServletRequest request)
        throws LoginException, LoginRedirectException {
    LuteceUser luteceUser = null;
    String strAuthProvider = request.getParameter(PARAMETER_AUTH_PROVIDER);

    if (strAuthProvider != null) {
        LuteceAuthentication myLuteceAuthentication = _mapAuthentications.get(strAuthProvider);

        if (myLuteceAuthentication != null) {
            if (AppLogService.isDebugEnabled()) {
                AppLogService.debug(
                        "Using " + myLuteceAuthentication.getAuthServiceName() + " for user " + strUserName);
            }

            luteceUser = myLuteceAuthentication.login(strUserName, strUserPassword, request);
        } else {
            AppLogService.error("Authentication null for key " + strAuthProvider);
            throw new LoginException(I18nService.getLocalizedString(PROPERTY_MESSAGE_NO_AUTHENTICATION_SELECTED,
                    request.getLocale()));
        }
    } else {
        throw new LoginException(I18nService.getLocalizedString(PROPERTY_MESSAGE_NO_AUTHENTICATION_SELECTED,
                request.getLocale()));
    }

    return luteceUser;
}

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

@Override
public boolean login() throws LoginException {
    boolean isLoggedIn;
    try {//from  ww w. j  a  v  a 2s  . c  o  m
        isLoggedIn = doLogin();
        if (!isLoggedIn) {
            SecurityLogger.audit("Username [" + user + "] failed LDAP authentication.");
        }
        return isLoggedIn;
    } catch (InvalidCharactersException e) {
        SecurityLogger.audit(e.getMessage());
        throw new LoginException(String.format(LOGIN_ERROR_MESSAGE, user) + e.getMessage());
    } catch (LoginException e) {
        throw new LoginException(String.format(LOGIN_ERROR_MESSAGE, user) + e.getMessage());
    }
}

From source file:com.vmware.identity.idm.server.provider.ldap.LdapWithAdMappingsProvider.java

@Override
public PrincipalId authenticate(PrincipalId principal, String password) throws LoginException {
    ValidateUtil.validateNotNull(principal, "principal");

    IIdmAuthStatRecorder idmAuthStatRecorder = this.createIdmAuthStatRecorderInstance(
            DiagnosticsContextFactory.getCurrentDiagnosticsContext().getTenantName(), ActivityKind.AUTHENTICATE,
            EventLevel.INFO, principal);
    idmAuthStatRecorder.start();//from  w  w  w  .  java 2  s. c om

    principal = this.normalizeAliasInPrincipal(principal);
    ILdapConnectionEx connection = null;

    try {
        connection = super.getConnection(getUserDN(principal), password, AuthenticationType.PASSWORD, false);
    } catch (Exception ex) {
        throw ((LoginException) new LoginException("Login failed").initCause(ex));
    } finally {
        if (connection != null) {
            connection.close();
        }
    }

    idmAuthStatRecorder.end();
    return principal;
}

From source file:com.vmware.identity.idm.server.provider.vmwdirectory.VMwareDirectoryProvider.java

@Override
public PrincipalId authenticate(PrincipalId principal, String password) throws LoginException {
    ValidateUtil.validateNotNull(principal, "principal");

    IIdmAuthStatRecorder idmAuthStatRecorder = this.createIdmAuthStatRecorderInstance(
            DiagnosticsContextFactory.getCurrentDiagnosticsContext().getTenantName(), ActivityKind.AUTHENTICATE,
            EventLevel.INFO, principal);
    idmAuthStatRecorder.start();/*  w ww.j a  v  a2  s.c  o m*/

    principal = this.normalizeAliasInPrincipal(principal);
    InvalidCredentialsLdapException srpEx = null;
    try {
        ILdapConnectionEx connection = null;
        try {
            connection = this.getConnection(principal.getUPN(), password, AuthenticationType.SRP, false);
        } catch (InvalidCredentialsLdapException ex) {
            logger.warn("Failed to authenticate using SRP binding", ex);
            srpEx = ex;
        } finally {
            if (connection != null) {
                connection.close();
                connection = null;
            }
        }
        if (srpEx != null) {
            String userDn = getUserDn(principal, true);
            if (userDn != null) {
                try {
                    logger.warn("The user is not SRP-enabled. Attempting to authenticate using simple bind.");
                    connection = this.getConnection(userDn, password, AuthenticationType.PASSWORD, false);
                } finally {
                    if (connection != null) {
                        connection.close();
                        connection = null;
                    }
                }
            } else {
                logger.warn("The user is SRP-enabled and failed to authenticate.");
                throw srpEx;
            }
        }
    } catch (Exception ex) {
        final LoginException loginException = new LoginException("Login failed");
        loginException.initCause(ex);
        throw loginException;
    }

    idmAuthStatRecorder.end();

    return principal;
}