Example usage for javax.security.auth.callback NameCallback getName

List of usage examples for javax.security.auth.callback NameCallback getName

Introduction

In this page you can find the example usage for javax.security.auth.callback NameCallback getName.

Prototype

public String getName() 

Source Link

Document

Get the retrieved name.

Usage

From source file:net.sf.jpam.jaas.JpamLoginModule.java

/**
 * Method to authenticate a <code>Subject</code> (phase 1).
 * <p/>//w w  w.ja v a  2s. c o m
 * <p> The implementation of this method authenticates
 * a <code>Subject</code>.  For example, it may prompt for
 * <code>Subject</code> information such
 * as a username and password and then attempt to verify the password.
 * This method saves the result of the authentication attempt
 * as private state within the LoginModule.
 * <p/>
 * <p/>
 *
 * @return true if the authentication succeeded, or false if this
 *         <code>LoginModule</code> should be ignored.
 * @throws javax.security.auth.login.LoginException
 *          if the authentication fails
 */
public boolean login() throws LoginException {
    pam = createPam();

    Callback[] callbacks = new Callback[2];
    String username = null;
    NameCallback nameCallback = new NameCallback("Enter Username: ");
    callbacks[0] = nameCallback;
    String credentials = null;
    PasswordCallback passwordCallback = new PasswordCallback("Enter Credentials: ", false);
    callbacks[1] = passwordCallback;

    try {
        callbackHandler.handle(callbacks);
    } catch (IOException e) {
        LOG.error("IOException handling login: " + e.getMessage(), e);
        throw new LoginException(e.getMessage());
    } catch (UnsupportedCallbackException e) {
        LOG.error("UnsupportedCallbackException handling login: " + e.getMessage(), e);
        throw new LoginException(e.getMessage());
    }
    username = nameCallback.getName();
    credentials = String.copyValueOf(passwordCallback.getPassword());
    boolean authenticated = false;
    PamReturnValue pamReturnValue = pam.authenticate(username, credentials);
    if (pamReturnValue.equals(PamReturnValue.PAM_SUCCESS)) {
        authenticated = true;
    } else if (pamReturnValue.equals(PamReturnValue.PAM_ACCT_EXPIRED)) {
        throw new AccountExpiredException(PamReturnValue.PAM_ACCT_EXPIRED.toString());
    } else if (pamReturnValue.equals(PamReturnValue.PAM_CRED_EXPIRED)) {
        throw new CredentialExpiredException(PamReturnValue.PAM_CRED_EXPIRED.toString());
    } else {
        throw new FailedLoginException(pamReturnValue.toString());
    }
    return authenticated;
}

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

/**
 * /*from  ww  w .ja  v  a 2s.c om*/
 * 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:org.jasig.cas.client.jaas.CasLoginModule.java

public boolean login() throws LoginException {
    log.debug("Performing login.");
    final NameCallback serviceCallback = new NameCallback("service");
    final PasswordCallback ticketCallback = new PasswordCallback("ticket", false);
    try {//ww w. ja  va 2 s  .  c  o m
        this.callbackHandler.handle(new Callback[] { ticketCallback, serviceCallback });
    } catch (final IOException e) {
        log.info("Login failed due to IO exception in callback handler: " + e);
        throw (LoginException) new LoginException("IO exception in callback handler: " + e).initCause(e);
    } catch (final UnsupportedCallbackException e) {
        log.info("Login failed due to unsupported callback: " + e);
        throw (LoginException) new LoginException(
                "Callback handler does not support PasswordCallback and TextInputCallback.").initCause(e);
    }

    if (ticketCallback.getPassword() != null) {
        this.ticket = new TicketCredential(new String(ticketCallback.getPassword()));
        final String service = CommonUtils.isNotBlank(serviceCallback.getName()) ? serviceCallback.getName()
                : this.service;

        if (this.cacheAssertions) {
            synchronized (ASSERTION_CACHE) {
                if (ASSERTION_CACHE.get(ticket) != null) {
                    log.debug("Assertion found in cache.");
                    this.assertion = (Assertion) ASSERTION_CACHE.get(ticket);
                }
            }
        }

        if (this.assertion == null) {
            log.debug("CAS assertion is null; ticket validation required.");
            if (CommonUtils.isBlank(service)) {
                log.info("Login failed because required CAS service parameter not provided.");
                throw new LoginException(
                        "Neither login module nor callback handler provided required service parameter.");
            }
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Attempting ticket validation with service=" + service + " and ticket=" + ticket);
                }
                this.assertion = this.ticketValidator.validate(this.ticket.getTicket(), service);

            } catch (final Exception e) {
                log.info("Login failed due to CAS ticket validation failure: " + e);
                throw (LoginException) new LoginException("CAS ticket validation failed: " + e).initCause(e);
            }
        }
        log.info("Login succeeded.");
    } else {
        log.info("Login failed because callback handler did not provide CAS ticket.");
        throw new LoginException("Callback handler did not provide CAS ticket.");
    }
    return true;
}

From source file:org.nuxeo.ecm.platform.login.test.DummyNuxeoLoginModule.java

@SuppressWarnings({ "unchecked" })
protected NuxeoPrincipal getPrincipal() throws LoginException {
    UserIdentificationInfo userIdent = null;

    // **** init the callbacks
    // Std login/password callbacks
    NameCallback nc = new NameCallback("Username: ", SecurityConstants.ANONYMOUS);
    PasswordCallback pc = new PasswordCallback("Password: ", false);

    // Nuxeo specific cb : handle LoginPlugin initialization
    UserIdentificationInfoCallback uic = new UserIdentificationInfoCallback();

    // JBoss specific cb : handle web=>ejb propagation
    // SecurityAssociationCallback ac = new SecurityAssociationCallback();
    // ObjectCallback oc = new ObjectCallback("UserInfo:");

    // **** handle callbacks
    // We can't check the callback handler class to know what will be
    // supported/*  w w w.ja v a  2  s. co m*/
    // because the cbh is wrapped by JAAS
    // => just try and swalow exceptions
    // => will be externalised to plugins via EP to avoid JBoss dependency
    boolean cb_handled = false;

    try {
        // only try this cbh when called from the web layer
        if (useUserIdentificationInfoCB) {
            callbackHandler.handle(new Callback[] { uic });
            // First check UserInfo CB return
            userIdent = uic.getUserInfo();
            cb_handled = true;
        }
    } catch (UnsupportedCallbackException e) {
        log.debug("UserIdentificationInfoCallback is not supported");
    } catch (IOException e) {
        log.warn("Error calling callback handler with UserIdentificationInfoCallback : " + e.getMessage());
    }

    Principal principal = null;
    Object credential = null;

    if (!cb_handled) {
        CallbackResult result = loginPluginManager.handleSpecifcCallbacks(callbackHandler);

        if (result != null && result.cb_handled) {
            if (result.userIdent != null && result.userIdent.containsValidIdentity()) {
                userIdent = result.userIdent;
                cb_handled = true;
            } else {
                principal = result.principal;
                credential = result.credential;
                if (principal != null) {
                    cb_handled = true;
                }
            }
        }
    }

    if (!cb_handled) {
        try {
            // Std CBH : will only works for L/P
            callbackHandler.handle(new Callback[] { nc, pc });
            cb_handled = true;
        } catch (UnsupportedCallbackException e) {
            LoginException le = new LoginException("Authentications Failure - " + e.getMessage());
            le.initCause(e);
        } catch (IOException e) {
            LoginException le = new LoginException("Authentications Failure - " + e.getMessage());
            le.initCause(e);
        }
    }

    try {
        // Login via the Web Interface : may be using a plugin
        if (userIdent != null && userIdent.containsValidIdentity()) {
            NuxeoPrincipal nxp = validateUserIdentity(userIdent);

            if (nxp != null) {
                sharedState.put("javax.security.auth.login.name", nxp.getName());
                sharedState.put("javax.security.auth.login.password", userIdent);
            }
            return nxp;
        }

        if (LoginComponent.isSystemLogin(principal)) {
            return new SystemPrincipal(principal.getName());
        }

        if (principal != null) { // a non null principal
            String password = null;
            if (credential instanceof char[]) {
                password = new String((char[]) credential);
            } else if (credential != null) {
                password = credential.toString();
            }
            return validateUsernamePassword(principal.getName(), password);
        } else { // we don't have a principal - try the username &
            // password
            String username = nc.getName();
            if (username == null) {
                return null;
            }
            char[] password = pc.getPassword();
            return validateUsernamePassword(username, password != null ? new String(password) : null);
        }
    } catch (LoginException e) {
        throw e;
    } catch (Exception e) {
        // jboss catches LoginException, so show it at least in the logs
        String msg = "Authentication failed: " + e.getMessage();
        log.error(msg, e);
        throw (LoginException) new LoginException(msg).initCause(e);
    }
}

From source file:org.nuxeo.ecm.platform.login.NuxeoLoginModule.java

@SuppressWarnings({ "unchecked" })
protected NuxeoPrincipal getPrincipal() throws LoginException {
    UserIdentificationInfo userIdent = null;

    // **** init the callbacks
    // Std login/password callbacks
    NameCallback nc = new NameCallback("Username: ", SecurityConstants.ANONYMOUS);
    PasswordCallback pc = new PasswordCallback("Password: ", false);

    // Nuxeo specific cb : handle LoginPlugin initialization
    UserIdentificationInfoCallback uic = new UserIdentificationInfoCallback();

    // JBoss specific cb : handle web=>ejb propagation
    // SecurityAssociationCallback ac = new SecurityAssociationCallback();
    // ObjectCallback oc = new ObjectCallback("UserInfo:");

    // **** handle callbacks
    // We can't check the callback handler class to know what will be
    // supported/*from   w  w  w . j av a  2 s  .c o  m*/
    // because the cbh is wrapped by JAAS
    // => just try and swalow exceptions
    // => will be externalised to plugins via EP to avoid JBoss dependency
    boolean cb_handled = false;

    try {
        // only try this cbh when called from the web layer
        if (useUserIdentificationInfoCB) {
            callbackHandler.handle(new Callback[] { uic });
            // First check UserInfo CB return
            userIdent = uic.getUserInfo();
            cb_handled = true;
        }
    } catch (UnsupportedCallbackException e) {
        log.debug("UserIdentificationInfoCallback is not supported");
    } catch (IOException e) {
        log.warn("Error calling callback handler with UserIdentificationInfoCallback : " + e.getMessage());
    }

    Principal principal = null;
    Object credential = null;

    if (!cb_handled) {
        CallbackResult result = loginPluginManager.handleSpecifcCallbacks(callbackHandler);

        if (result != null && result.cb_handled) {
            if (result.userIdent != null && result.userIdent.containsValidIdentity()) {
                userIdent = result.userIdent;
                cb_handled = true;
            } else {
                principal = result.principal;
                credential = result.credential;
                if (principal != null) {
                    cb_handled = true;
                }
            }
        }
    }

    if (!cb_handled) {
        try {
            // Std CBH : will only works for L/P
            callbackHandler.handle(new Callback[] { nc, pc });
            cb_handled = true;
        } catch (UnsupportedCallbackException e) {
            LoginException le = new LoginException("Authentications Failure - " + e.getMessage());
            le.initCause(e);
        } catch (IOException e) {
            LoginException le = new LoginException("Authentications Failure - " + e.getMessage());
            le.initCause(e);
        }
    }

    // Login via the Web Interface : may be using a plugin
    if (userIdent != null && userIdent.containsValidIdentity()) {
        NuxeoPrincipal nxp = validateUserIdentity(userIdent);

        if (nxp != null) {
            sharedState.put("javax.security.auth.login.name", nxp.getName());
            sharedState.put("javax.security.auth.login.password", userIdent);
        }
        return nxp;
    }

    if (LoginComponent.isSystemLogin(principal)) {
        return new SystemPrincipal(principal.getName());
    }
    // if (principal instanceof NuxeoPrincipal) { // a nuxeo principal
    // return validatePrincipal((NuxeoPrincipal) principal);
    // } else
    if (principal != null) { // a non null principal
        String password = null;
        if (credential instanceof char[]) {
            password = new String((char[]) credential);
        } else if (credential != null) {
            password = credential.toString();
        }
        return validateUsernamePassword(principal.getName(), password);
    } else { // we don't have a principal - try the username &
        // password
        String username = nc.getName();
        if (username == null) {
            return null;
        }
        char[] password = pc.getPassword();
        return validateUsernamePassword(username, password != null ? new String(password) : null);
    }
}