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.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

/**
 * Gets credentials by calling {@link #getCallBackAuth()}, then performs {@link #authenticate(String, Object)}
 *
 * @return true if authenticated/*from   ww  w  .  j  a  va 2  s .  c  o m*/
 * @throws LoginException
 */
@Override
public boolean login() throws LoginException {
    try {
        Object[] userPass = getCallBackAuth();
        if (null == userPass || userPass.length < 2) {
            setAuthenticated(false);
            throw new FailedLoginException();
        }
        String name = (String) userPass[0];
        Object pass = userPass[1];
        boolean authenticated = authenticate(name, pass);
        setAuthenticated(authenticated);

        if (!isAuthenticated()) {
            throw new FailedLoginException();
        }
        return isAuthenticated();
    } catch (UnsupportedCallbackException e) {
        throw new LoginException("Error obtaining callback information.");
    } catch (IOException e) {
        if (_debug) {
            e.printStackTrace();
        }
        throw new LoginException("IO Error performing login.");
    }
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

/**
 *
 * @return Return the object[] containing username and password, by using the callback mechanism
 *
 * @throws IOException/*w ww . j ava  2s  . c om*/
 * @throws UnsupportedCallbackException
 * @throws LoginException
 */
protected Object[] getCallBackAuth() throws IOException, UnsupportedCallbackException, LoginException {
    if (getCallbackHandler() == null) {
        throw new LoginException("No callback handler");
    }

    Callback[] callbacks = configureCallbacks();
    getCallbackHandler().handle(callbacks);

    String webUserName = ((NameCallback) callbacks[0]).getName();
    Object webCredential = ((ObjectCallback) callbacks[1]).getObject();
    if (webCredential == null) {
        webCredential = ((PasswordCallback) callbacks[2]).getPassword();
    }
    return new Object[] { webUserName, webCredential };
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

/**
 * since ldap uses a context bind for valid authentication checking, we
 * override login()/*  w  ww.ja v a 2 s .c o m*/
 * <br>
 * if credentials are not available from the users context or if we are
 * forcing the binding check then we try a binding authentication check,
 * otherwise if we have the users encoded password then we can try
 * authentication via that mechanic
 * @param webUserName user
 * @param webCredential password
 *
 *
 * @return true if authenticated
 * @throws LoginException
 */
protected boolean authenticate(final String webUserName, final Object webCredential) throws LoginException {
    try {
        if (isEmptyOrNull(webUserName) || isEmptyOrNull(webCredential)
                || (webCredential instanceof char[] && ((char[]) webCredential).length == 0)) {
            LOG.info("empty username or password not allowed");
            setAuthenticated(false);
            return isAuthenticated();
        }

        loginAttempts++;

        if (_reportStatistics) {
            DecimalFormat percentHit = new DecimalFormat("#.##");
            LOG.info("Login attempts: " + loginAttempts + ", Hits: " + userInfoCacheHits + ", Ratio: "
                    + percentHit.format((double) userInfoCacheHits / loginAttempts * 100f) + "%.");
        }

        if (_forceBindingLogin) {
            return bindingLogin(webUserName, webCredential);
        }

        // This sets read and the credential
        UserInfo userInfo = getUserInfo(webUserName);

        if (userInfo == null) {
            setAuthenticated(false);
            return false;
        }

        JAASUserInfo jaasUserInfo = new JAASUserInfo(userInfo);
        jaasUserInfo.fetchRoles(); //must run this otherwise will throw NPE later
        setCurrentUser(jaasUserInfo);

        if (webCredential instanceof String) {
            return credentialLogin(Credential.getCredential((String) webCredential));
        }

        return credentialLogin(webCredential);
    } catch (UnsupportedCallbackException e) {
        throw new LoginException("Error obtaining callback information.");
    } catch (IOException e) {
        if (_debug) {
            e.printStackTrace();
        }
        throw new LoginException("IO Error performing login.");
    } catch (LoginException e) {
        throw e;
    } catch (Exception e) {
        if (_debug) {
            e.printStackTrace();
        }
        throw new LoginException("Error obtaining user info.");
    }
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

/**
 * binding authentication check This methode of authentication works only if
 * the user branch of the DIT (ldap tree) has an ACI (acces control
 * instruction) that allow the access to any user or at least for the user
 * that logs in.//from   www.  j a  v a2s.com
 *
 * @param username
 * @param password
 * @return
 * @throws LoginException
 */
@SuppressWarnings("unchecked")
protected boolean bindingLogin(String username, Object password) throws LoginException, NamingException {
    final String cacheToken = Credential.MD5.digest(username + ":" + password.toString());
    if (_cacheDuration > 0) { // only worry about caching if there is a cacheDuration set.
        CachedUserInfo cached = USERINFOCACHE.get(cacheToken);
        if (cached != null) {
            if (System.currentTimeMillis() < cached.expires) {
                debug("Cache Hit for " + username + ".");
                userInfoCacheHits++;
                JAASUserInfo jaasUserInfo = new JAASUserInfo(cached.userInfo);
                try {
                    jaasUserInfo.fetchRoles();
                } catch (Exception ex) {
                    if (_debug) {
                        LOG.debug("Failed to fetch roles", ex);
                    }
                    throw new LoginException("Error obtaining user info.");
                }
                setCurrentUser(jaasUserInfo);
                setAuthenticated(true);
                return true;
            } else {
                LOG.info("Cache Eviction for " + username + ".");
                USERINFOCACHE.remove(cacheToken);
            }
        } else {
            debug("Cache Miss for " + username + ".");
        }
    }

    SearchResult searchResult = findUser(username);

    String userDn = searchResult.getNameInNamespace();

    LOG.info("Attempting authentication: " + userDn);
    DirContext dirContext = createBindUserDirContext(userDn, password);
    setDemographicAttributes(searchResult.getAttributes());

    // use _rootContext to find roles, if configured to doso
    if (_forceBindingLoginUseRootContextForRoles) {
        dirContext = _rootContext;
        debug("Using _rootContext for role lookup.");
    }
    List roles = getUserRolesByDn(dirContext, userDn, username);

    UserInfo userInfo = new UserInfo(username, new Password(password.toString()), roles);
    if (_cacheDuration > 0) {
        USERINFOCACHE.put(cacheToken,
                new CachedUserInfo(userInfo, System.currentTimeMillis() + _cacheDuration));
        debug("Adding " + username + " set to expire: " + System.currentTimeMillis() + _cacheDuration);
    }
    JAASUserInfo jaasUserInfo = new JAASUserInfo(userInfo);
    try {
        jaasUserInfo.fetchRoles();
    } catch (Exception ex) {
        if (_debug) {
            LOG.debug("Failed to fetch roles", ex);
        }
        throw new LoginException("Error obtaining user info.");
    }
    setCurrentUser(jaasUserInfo);
    setAuthenticated(true);
    return true;
}

From source file:iracing.webapi.IracingWebApi.java

/**
 * // w w  w. j av a  2s. c om
 * @return a login response code
 * @throws IOException
 * @throws LoginException 
 * @see #LOGIN_RESPONSE_SUCCESS
 * @see #LOGIN_RESPONSE_CONNECTION_ERROR
 * @see #LOGIN_RESPONSE_DOWN_FOR_MAINTAINENCE
 * @see #LOGIN_RESPONSE_FAILED_CREDENTIALS
 */
public LoginResponse login() throws IOException, LoginException {
    try {
        installCerts();
    } catch (Exception e1) {
        e1.printStackTrace();
        throw new LoginException("error whilst attempting to install SSL certificates");
    }

    System.setProperty("javax.net.ssl.trustStore", "jssecacerts");
    System.setProperty("javax.net.ssl.trustStorePassword", CERT_STORE_PASSWORD);

    if (loginRequiredHandler == null)
        return LoginResponse.ConfigError;
    IracingLoginCredentials creds = new IracingLoginCredentials();
    if (!loginRequiredHandler.onLoginCredentialsRequired(creds))
        return LoginResponse.CredentialsError;
    String encodedUsername = URLEncoder.encode(creds.getEmailAddress(), "UTF-8");
    String encodedPW = URLEncoder.encode(creds.getPassword(), "UTF-8");

    String urltext = LOGIN_URL + "?username=" + encodedUsername + "&password=" + encodedPW; // + "&utcoffset=-60&todaysdate=";

    URL url = new URL(urltext);

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    conn.addRequestProperty("Content-Length", "0");

    conn.setInstanceFollowRedirects(false);
    HttpsURLConnection.setFollowRedirects(false);

    try {
        conn.connect();
    } catch (Exception e) {
        e.printStackTrace();
        throw new LoginException(e.getMessage());
    }

    if (isMaintenancePage(conn))
        return LoginResponse.DownForMaintenance;

    String headerName;
    for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
        if (headerName.equalsIgnoreCase(SET_COOKIE)) {
            addToCookieMap(conn.getHeaderField(i));
        } else {
            if (!headerName.equals("Location")) {
                continue;
            }
            String location2 = conn.getHeaderField(i);

            if (location2.indexOf("failedlogin") != -1) {
                throw new LoginException("You have been directed to the failed login page");
            }
        }
    }
    createCookieFromMap();

    conn.disconnect();

    return LoginResponse.Success;
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

@SuppressWarnings("unchecked")
private SearchResult findUser(String username) throws NamingException, LoginException {
    SearchControls ctls = new SearchControls();
    ctls.setCountLimit(1);/* w  ww .  j a v  a 2 s  .  c o  m*/
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = OBJECT_CLASS_FILTER;

    debug("Searching for users with filter: \'" + filter + "\'" + " from base dn: " + _userBaseDn);

    Object[] filterArguments = new Object[] { _userObjectClass, _userIdAttribute, username };
    NamingEnumeration results = _rootContext.search(_userBaseDn, filter, filterArguments, ctls);

    debug("Found user?: " + results.hasMoreElements());

    if (!results.hasMoreElements()) {
        throw new LoginException("User not found.");
    }

    return (SearchResult) results.nextElement();
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

public boolean commit() throws LoginException {
    try {/*w  ww  .ja v a  2s  .c o m*/
        _rootContext.close();
    } catch (NamingException e) {
        throw new LoginException("error closing root context: " + e.getMessage());
    }
    if (_userFirstName != null)
        getSubject().getPrincipals().add(new LdapFirstNamePrincipal(_userFirstName));
    if (_userLastName != null)
        getSubject().getPrincipals().add(new LdapLastNamePrincipal(_userLastName));
    if (_userEmail != null)
        getSubject().getPrincipals().add(new LdapEmailPrincipal(_userEmail));

    return super.commit();
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

public boolean abort() throws LoginException {
    try {//from  w  ww.  j  a  v a  2 s  .c o m
        _rootContext.close();
    } catch (NamingException e) {
        throw new LoginException("error closing root context: " + e.getMessage());
    }

    return super.abort();
}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.SchedulerStateRest.java

/**
 * Login to the scheduler using a form containing 2 fields (username and
 * password).//from   w w  w.  j  av a2 s  . c  om
 *
 * @param username
 *            username
 * @param password
 *            password
 * @return the session id associated to the login.
 * @throws LoginException
 */
@Override
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("login")
@Produces("application/json")
public String login(@FormParam("username") String username, @FormParam("password") String password)
        throws LoginException, SchedulerRestException {
    try {
        if ((username == null) || (password == null)) {
            throw new LoginException("Empty login/password");
        }
        Session session = sessionStore.create(username);
        session.connectToScheduler(new CredData(username, password));
        logger.info("Binding user " + username + " to session " + session.getSessionId());
        return session.getSessionId();
    } catch (ActiveObjectCreationException e) {
        throw new SchedulerRestException(e);
    } catch (SchedulerException e) {
        throw new SchedulerRestException(e);
    } catch (NodeException e) {
        throw new SchedulerRestException(e);
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.SchedulerStateRest.java

/**
 * Login to the scheduler using a multipart form can be used either by
 * submitting 2 fields ({@code username} and {@code password}) or by sending
 * a credential file with field name {@code credential}.
 *
 * @return the session id associated to this new connection.
 * @throws KeyException//from   www .  j ava  2  s.  com
 * @throws LoginException
 * @throws SchedulerRestException
 */
@Override
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("login")
@Produces("application/json")
public String loginWithCredential(@MultipartForm LoginForm multipart)
        throws LoginException, KeyException, SchedulerRestException {
    try {
        Session session;
        if (multipart.getCredential() != null) {
            Credentials credentials;
            try {
                session = sessionStore.createUnnamedSession();
                credentials = Credentials.getCredentials(multipart.getCredential());
                session.connectToScheduler(credentials);
            } catch (IOException e) {
                throw new LoginException(e.getMessage());
            }
        } else {
            if ((multipart.getUsername() == null) || (multipart.getPassword() == null)) {
                throw new LoginException("empty login/password");
            }

            session = sessionStore.create(multipart.getUsername());
            CredData credData = new CredData(CredData.parseLogin(multipart.getUsername()),
                    CredData.parseDomain(multipart.getUsername()), multipart.getPassword(),
                    multipart.getSshKey());
            session.connectToScheduler(credData);
        }

        return session.getSessionId();

    } catch (PermissionException e) {
        throw new SchedulerRestException(e);
    } catch (ActiveObjectCreationException e) {
        throw new SchedulerRestException(e);
    } catch (SchedulerException e) {
        throw new SchedulerRestException(e);
    } catch (NodeException e) {
        throw new SchedulerRestException(e);
    }
}