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:com.trailmagic.user.UserLoginModule.java

public boolean commit() throws LoginException {
    s_log.debug("commit() called!");
    if (m_success) {
        if (m_subject.isReadOnly()) {
            throw new LoginException("Subject is read-only");
        }/*  w w w  . j a  v  a  2s  .c  o  m*/
        try {
            m_subject.getPrincipals().addAll(m_principals);
            m_principals.clear();
        } catch (Exception e) {
            throw new LoginException(e.getMessage());
        }
    } else {
        m_principals.clear();
    }
    s_log.debug("returning true!");
    return true;
}

From source file:com.vaushell.gfmongodb.MongoDbUserRealm.java

/**
 * Authenticate user.// ww w  .jav  a2s.  co  m
 *
 * @param username Username.
 * @param givenPassword Password
 * @return List of groups.
 * @throws LoginException
 */
String[] authenticate(final String username, final char[] givenPassword) throws LoginException {
    if (username == null || username.length() <= 0 || givenPassword == null || givenPassword.length <= 0) {
        throw new LoginException("username or password is empty");
    }

    final QueryBuilder builder = QueryBuilder.start(getProperty(PARAM_USERNAME)).is(username);
    final DBObject user = usersCollection.findOne(builder.get());
    if (user == null) {
        throw new LoginException("cannot find user with username '" + username + "'");
    }

    final String databasePassword = (String) user.get(getProperty(PARAM_PASSWORD));
    if (databasePassword == null || databasePassword.length() <= 0) {
        throw new LoginException("cannot find nonempty password for username '" + username + "'");
    }

    final String transformedPassword = DigestUtils.sha256Hex(new String(givenPassword));
    if (!databasePassword.equals(transformedPassword)) {
        throw new LoginException("password is wrong for username '" + username + "'");
    }

    final List<String> groups = getGroups(user);
    return groups.toArray(new String[groups.size()]);
}

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");
    }/* ww  w .j a  va 2s .  c  o 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;
}

From source file:org.betaconceptframework.astroboa.security.jaas.AstroboaLoginModule.java

/**
 * Override login to provide extra checks in case user credentials are
 * correct//ww w.j  a va 2 s  . c o m
 */
public boolean login() throws LoginException {

    boolean loginIsSuccessful = internalLogin();

    if (loginIsSuccessful == true) {

        //Load Person and execute some extra checks
        //Normally loggedInPerson must have already been initialized

        /*if (BooleanUtils.isFalse(loggedInPerson.getUserData().getAccountNonLocked())) {
           throw new AccountLockedException(getUsername());
        }*/

        if (!loggedInPerson.isEnabled()) {
            throw new AccountNotFoundException(getUsername());
        }

        /*if (BooleanUtils.isFalse(loggedInPerson.getUserData().getAccountNonExpired())) {
           throw new AccountExpiredException(getUsername());
        }
                
        if (BooleanUtils.isFalse(loggedInPerson.getUserData().getCredentialsNonExpired())) {
           throw new CredentialExpiredException(getUsername());
        }*/

        return true;
    } else {
        throw new LoginException(getUsername());
    }

}

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

/**
 * Override login to provide extra checks in case user credentials are
 * correct/*from  ww w  .j  a va  2  s.c o m*/
 * @return 
 */
public Subject login() throws LoginException {

    boolean loginIsSuccessful = internalLogin();

    if (loginIsSuccessful == true) {

        if (!loggedInPerson.isEnabled()) {
            throw new AccountNotFoundException(getUsername());
        }

        //Add identity 
        addIdentityPrincipalToSubject();

        //Add PersonUserIdPrincipal to subject
        addPersonUserIdPrincipalToSubject();

        //Add display name principal
        addDisplayNamePrincipalToSubject();

        //Add roles to subject
        addRolesToSubject();

        return subject;
    } else {
        throw new LoginException(getUsername());
    }

}

From source file:org.apache.ranger.authentication.unix.jaas.PamLoginModule.java

@Override
public boolean commit() throws LoginException {
    if (_authSucceeded == false) {
        return false;
    }/*from   w w w  . ja v a  2  s  .  co m*/

    if (_subject.isReadOnly()) {
        cleanup();
        throw new LoginException("Subject is read-only");
    }

    Set<Principal> principals = _subject.getPrincipals();
    if (principals.contains(_principal) == false) {
        principals.add(_principal);
    }

    return true;
}

From source file:org.getobjects.jaas.GoDefaultLoginModule.java

/**
 * This is the primary JAAS Phase 1 entry point. The default implementation
 * grabs login/username from the CallbackHandler (eg the one provided by the
 * GoHTTPAuthenticator) and calls loginWithUsernameAndPassword() with this
 * information.//from w  ww .j  ava2 s. c  o  m
 * 
 * @return true if authentication was successful, false otherwise
 * @throws LoginException
 */
public boolean login() throws LoginException {
    if (this.handler == null)
        throw new LoginException("missing JAAS callback handler!");

    return this.loginWithUsernameAndPassword();
}

From source file:org.chililog.server.engine.JAASLoginModule.java

/**
 * <p>//from  w w  w .j a  v a 2  s  .  c  o  m
 * We check the credentials against the repository. By convention, the username is the repository name and the
 * password is either the publisher or subscriber password. The role assigned to the user is constructed from the
 * combination of username and publisher password.
 * </p>
 * 
 * @return Returns true if this method succeeded, or false if this LoginModule should be ignored.
 */
public boolean login() throws LoginException {
    try {
        //
        // This code is from org.hornetq.spi.core.security.JAASSecurityManager.getAuthenticatedSubject();
        // It is how HornetQ uses JAAS to authenticate
        //
        // Subject subject = new Subject();
        // if (user != null)
        // {
        // subject.getPrincipals().add(principal);
        // }
        // subject.getPrivateCredentials().add(passwordChars);
        // LoginContext lc = new LoginContext(configurationName, subject, callbackHandler, config);

        // Get the user name
        Iterator<Principal> iterator = _subject.getPrincipals().iterator();
        String username = iterator.next().getName();
        if (StringUtils.isBlank(username)) {
            throw new FailedLoginException("Username is requried.");
        }

        // Get the password
        Iterator<char[]> iterator2 = _subject.getPrivateCredentials(char[].class).iterator();
        char[] passwordChars = iterator2.next();
        String password = new String(passwordChars);
        if (StringUtils.isBlank(password)) {
            throw new FailedLoginException("Password is requried.");
        }

        // Check if system user
        if (username.equals(_systemUsername) && password.equals(_systemPassword)) {
            Group roles = new SimpleGroup("Roles");
            roles.addMember(new SimplePrincipal(UserBO.SYSTEM_ADMINISTRATOR_ROLE_NAME));
            _subject.getPrincipals().add(roles);
            return true;
        }

        // Let's validate non-system user
        DB db = MongoConnection.getInstance().getConnection();
        UserBO user = UserController.getInstance().tryGetByUsername(db, username);
        if (user == null) {
            throw new FailedLoginException("Invalid username or password.");
        }
        if (StringUtils.isBlank(password) || !user.validatePassword(password)) {
            throw new FailedLoginException("Invalid username or password.");
        }

        // Add role
        Group roles = new SimpleGroup("Roles");
        for (String role : user.getRoles()) {
            roles.addMember(new SimplePrincipal(role));
        }
        _subject.getPrincipals().add(roles);

        // OK
        return true;
    } catch (Exception ex) {
        throw new LoginException(ex.getMessage());
    }
}