Example usage for javax.security.auth.callback CallbackHandler CallbackHandler

List of usage examples for javax.security.auth.callback CallbackHandler CallbackHandler

Introduction

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

Prototype

CallbackHandler

Source Link

Usage

From source file:Main.java

public static void setupSunPKCS11Provider(String pkcs11LibPath, final char[] password) {
    // Prevents installing the provider twice.
    if (Security.getProvider("SunPKCS11-verinice") != null)
        return;/*from  w  w  w .ja  v  a2  s. c  o m*/

    // If the user enabled anything PKCS#11 related we need to lead the
    // PKCS#11 library and add its
    // provider.
    String configFile = createPKCS11ConfigFile(pkcs11LibPath);
    if (configFile != null) {
        // The availability of this class in an OSGi environment depends on
        // a system property. If
        // get errors of this class not being available check that you have
        // -Dosgi.parentClassloader=ext
        // in your VM arguments.
        SunPKCS11 p = new SunPKCS11(configFile);
        p.setCallbackHandler(new CallbackHandler() {

            @Override
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                ((PasswordCallback) callbacks[0]).setPassword(password);
            }
        });
        Security.addProvider(p);
    }
}

From source file:com.tethrnet.manage.util.ExternalAuthUtil.java

/**
 * external auth login method//from   www.ja  v  a2s .co m
 *
 * @param auth contains username and password
 * @return auth token if success
 */
public static String login(final Auth auth) {

    String authToken = null;
    if (externalAuthEnabled && auth != null && StringUtils.isNotEmpty(auth.getUsername())
            && StringUtils.isNotEmpty(auth.getPassword())) {

        Connection con = null;
        try {
            CallbackHandler handler = new CallbackHandler() {

                @Override
                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                    for (Callback callback : callbacks) {
                        if (callback instanceof NameCallback) {
                            ((NameCallback) callback).setName(auth.getUsername());
                        } else if (callback instanceof PasswordCallback) {
                            ((PasswordCallback) callback).setPassword(auth.getPassword().toCharArray());
                        }
                    }
                }
            };

            try {
                LoginContext loginContext = new LoginContext(JAAS_MODULE, handler);
                //will throw exception if login fail
                loginContext.login();
                Subject subject = loginContext.getSubject();

                con = DBUtils.getConn();
                User user = AuthDB.getUserByUID(con, auth.getUsername());

                if (user == null) {
                    user = new User();

                    user.setUserType(User.ADMINISTRATOR);
                    user.setUsername(auth.getUsername());

                    //set email
                    if (auth.getUsername().contains("@")) {
                        user.setEmail(auth.getUsername());
                    }

                    user.setId(UserDB.insertUser(con, user));
                }

                authToken = UUID.randomUUID().toString();
                user.setAuthToken(authToken);
                user.setAuthType(Auth.AUTH_EXTERNAL);
                //set auth token
                AuthDB.updateLogin(con, user);

            } catch (LoginException e) {
                //auth failed return empty
                authToken = null;
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }

        DBUtils.closeConn(con);
    }

    return authToken;
}

From source file:com.keybox.manage.util.ExternalAuthUtil.java

/**
 * external auth login method/*w w  w . j  a  v  a2s  . c  o m*/
 *
 * @param auth contains username and password
 * @return auth token if success
 */
public static String login(final Auth auth) {

    String authToken = null;
    if (externalAuthEnabled && auth != null && StringUtils.isNotEmpty(auth.getUsername())
            && StringUtils.isNotEmpty(auth.getPassword())) {

        Connection con = null;
        try {
            CallbackHandler handler = new CallbackHandler() {

                @Override
                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                    for (Callback callback : callbacks) {
                        if (callback instanceof NameCallback) {
                            ((NameCallback) callback).setName(auth.getUsername());
                        } else if (callback instanceof PasswordCallback) {
                            ((PasswordCallback) callback).setPassword(auth.getPassword().toCharArray());
                        }
                    }
                }
            };

            try {
                LoginContext loginContext = new LoginContext(JAAS_MODULE, handler);
                //will throw exception if login fail
                loginContext.login();
                Subject subject = loginContext.getSubject();

                con = DBUtils.getConn();
                User user = AuthDB.getUserByUID(con, auth.getUsername());

                if (user == null) {
                    user = new User();

                    user.setUserType(User.ADMINISTRATOR);
                    user.setUsername(auth.getUsername());

                    //if it looks like name is returned default it 
                    for (Principal p : subject.getPrincipals()) {
                        if (p.getName().contains(" ")) {
                            String[] name = p.getName().split(" ");
                            if (name.length > 1) {
                                user.setFirstNm(name[0]);
                                user.setLastNm(name[name.length - 1]);
                            }
                        }
                    }

                    //set email
                    if (auth.getUsername().contains("@")) {
                        user.setEmail(auth.getUsername());
                    }

                    user.setId(UserDB.insertUser(con, user));
                }

                authToken = UUID.randomUUID().toString();
                user.setAuthToken(authToken);
                user.setAuthType(Auth.AUTH_EXTERNAL);
                //set auth token
                AuthDB.updateLogin(con, user);

            } catch (LoginException e) {
                //auth failed return empty
                authToken = null;
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }

        DBUtils.closeConn(con);
    }

    return authToken;
}

From source file:com.vmware.identity.openidconnect.client.GSSTestUtils.java

static LoginContext getLoginCtx(final PrincipalId validAdUser, final char[] userPass,
        javax.security.auth.Subject jaasSubject) throws LoginException {
    return new LoginContext("SampleLoginContext", jaasSubject, new CallbackHandler() {
        @Override/*from   w w w  . ja  va2 s . c o  m*/
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            String userName = String.format("%s@%s", validAdUser.getName(), validAdUser.getDomain());
            for (Callback callback : callbacks) {
                if (callback instanceof NameCallback) {
                    ((NameCallback) callback).setName(userName);
                } else if (callback instanceof PasswordCallback) {
                    ((PasswordCallback) callback).setPassword(userPass);
                }
            }
        }
    },

            new Configuration() {
                @Override
                public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
                    Map<String, String> config = new HashMap<String, String>();
                    config.put("useTicketCache", "false");
                    return new AppConfigurationEntry[] {
                            new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
                                    AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, config) };
                }
            });
}

From source file:io.fabric8.maven.impl.MavenSecureHttpContext.java

public Subject doAuthenticate(final String username, final String password) {
    try {/*from   www. j av  a  2  s  .  co  m*/
        Subject subject = new Subject();
        LoginContext loginContext = new LoginContext(realm, subject, new CallbackHandler() {
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (int i = 0; i < callbacks.length; i++) {
                    if (callbacks[i] instanceof NameCallback) {
                        ((NameCallback) callbacks[i]).setName(username);
                    } else if (callbacks[i] instanceof PasswordCallback) {
                        ((PasswordCallback) callbacks[i]).setPassword(password.toCharArray());
                    } else {
                        throw new UnsupportedCallbackException(callbacks[i]);
                    }
                }
            }
        });
        loginContext.login();
        if (role != null && role.length() > 0) {
            String clazz = "org.apache.karaf.jaas.boot.principal.RolePrincipal";
            String name = role;
            int idx = role.indexOf(':');
            if (idx > 0) {
                clazz = role.substring(0, idx);
                name = role.substring(idx + 1);
            }
            boolean found = false;
            for (Principal p : subject.getPrincipals()) {
                if (p.getClass().getName().equals(clazz) && p.getName().equals(name)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new FailedLoginException("User does not have the required role " + role);
            }
        }
        return subject;
    } catch (AccountException e) {
        LOGGER.warn("Account failure", e);
        return null;
    } catch (LoginException e) {
        LOGGER.debug("Login failed", e);
        return null;
    } catch (GeneralSecurityException e) {
        LOGGER.error("General Security Exception", e);
        return null;
    }
}

From source file:davmail.http.DavGatewaySSLProtocolSocketFactory.java

private KeyStore.ProtectionParameter getProtectionParameter(String password) {
    if (password != null && password.length() > 0) {
        // password provided: create a PasswordProtection
        return new KeyStore.PasswordProtection(password.toCharArray());
    } else {//w  ww  .j  a  v  a 2  s  . c  o  m
        // request password at runtime through a callback
        return new KeyStore.CallbackHandlerProtection(new CallbackHandler() {
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                if (callbacks.length > 0 && callbacks[0] instanceof PasswordCallback) {
                    PasswordPromptDialog passwordPromptDialog = new PasswordPromptDialog(
                            ((PasswordCallback) callbacks[0]).getPrompt());
                    ((PasswordCallback) callbacks[0]).setPassword(passwordPromptDialog.getPassword());
                }
            }
        });
    }
}

From source file:com.vmware.o11n.plugin.powershell.remote.impl.winrm.KerberosTokenGenerator.java

private void login(final NTUser userName, final String password) throws LoginException {
    this.subject = new Subject();
    LoginContext login;/*from w  ww . ja v  a 2s . c  o  m*/
    login = new LoginContext("", subject, new CallbackHandler() {

        @Override
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback callback : callbacks) {
                if (callback instanceof NameCallback) {
                    //We may need some more complete mapping between AD user domain and Kerberos realms  
                    String kerbUserSPN = userName.getUserName();
                    if (StringUtils.isNotBlank(userName.getDomain())) {
                        kerbUserSPN += "@" + userName.getDomain().toUpperCase();
                    }

                    log.debug("Kerberos login name: " + kerbUserSPN);
                    ((NameCallback) callback).setName(kerbUserSPN);
                } else if (callback instanceof PasswordCallback) {
                    ((PasswordCallback) callback).setPassword(password.toCharArray());
                }
            }
        }
    }, new Configuration() {
        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            Map<String, String> config = new HashMap<String, String>();
            config.put("useTicketCache", "false");

            return new AppConfigurationEntry[] {
                    new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, config) };
        }
    });
    login.login();

}

From source file:org.apache.brooklyn.security.StockSecurityProviderTest.java

private LoginContext doLogin(final String username, final String password) throws LoginException {
    assertRealmRegisteredEventually(WEBCONSOLE_REALM);
    LoginContext lc = new LoginContext(WEBCONSOLE_REALM, new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (int i = 0; i < callbacks.length; i++) {
                Callback callback = callbacks[i];
                if (callback instanceof PasswordCallback) {
                    PasswordCallback passwordCallback = (PasswordCallback) callback;
                    passwordCallback.setPassword(password.toCharArray());
                } else if (callback instanceof NameCallback) {
                    NameCallback nameCallback = (NameCallback) callback;
                    nameCallback.setName(username);
                }/*from  ww w  . ja  va 2 s .c o m*/
            }
        }
    });
    lc.login();
    return lc;
}

From source file:edu.mit.oidc.web.StatusEndpoint.java

/**
 * Make a test call to the kerberos server to see if it's reachable.
 * /*from   www . j  a  va2s.  c o  m*/
 * @return
 */
private Map<String, Map<String, Object>> getKerbStatus() {
    Map<String, Object> status = new HashMap<>();

    try {

        Krb5LoginModule krb = new Krb5LoginModule();

        Subject subject = new Subject();
        CallbackHandler callbackHandler = new CallbackHandler() {
            @Override
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                // ignore everything
            }
        };
        Map<String, Object> sharedState = ImmutableMap.of();
        Map<String, Object> options = new ImmutableMap.Builder().put("refreshKrb5Config", "true")
                .put("useTicketCache", "false").put("doNotPrompt", "true").put("useKeyTab", "true")
                .put("keyTab", getKeyTab()).put("storeKey", "false").put("principal", getPrincipal())
                .put("isInitiator", "true").build();

        krb.initialize(subject, callbackHandler, sharedState, options);

        boolean login = krb.login();
        status.put("success", login);
        status.put("subject", subject.getPrincipals());

    } catch (Exception e) {
        status.put("success", false);
        status.put("error", e.getMessage());
    }

    return ImmutableMap.of("kerberos", status);
}

From source file:controller.CCInstance.java

public final ArrayList<CCAlias> loadKeyStoreAndAliases()
        throws LibraryNotLoadedException, KeyStoreNotLoadedException, CertificateException, KeyStoreException,
        LibraryNotFoundException, AliasException {
    String pkcs11config = "name = SmartCard\n library = ";
    String path = null;//from  w w  w .  j a  va  2s.c  om
    if (SystemUtils.IS_OS_WINDOWS) {
        path = System.getenv("HOMEDRIVE") + "\\windows\\system32\\pteidpkcs11.dll";
    } else if (SystemUtils.IS_OS_LINUX) {
        path = "/usr/local/lib/libpteidpkcs11.so";
    } else if (SystemUtils.IS_OS_MAC_OSX) {
        path = "/usr/local/lib/pteidpkcs11.bundle";
    }

    if (null == path) {
        throw new LibraryNotLoadedException(Bundle.getBundle().getString("unknownOS"));
    } else if (new File(path).exists()) {
        pkcs11config += path;
    } else {
        String res = userLoadLibraryPKCS11();
        if (null != res) {
            pkcs11config += res;
        }
        throw new LibraryNotFoundException(Bundle.getBundle().getString("libraryNotFound"));
    }
    final byte[] pkcs11configBytes;
    try {
        pkcs11configBytes = pkcs11config.getBytes();
    } catch (Exception eiie) {
        Logger.getLogger().addEntry(eiie);
        throw new LibraryNotFoundException(Bundle.getBundle().getString("libraryDoesNotExist"));
    }
    final ByteArrayInputStream configStream = new ByteArrayInputStream(pkcs11configBytes);
    try {
        pkcs11Provider = new sun.security.pkcs11.SunPKCS11(configStream);
        pkcs11Provider.setCallbackHandler(new CallbackHandler() {

            @Override
            public void handle(javax.security.auth.callback.Callback[] callbacks)
                    throws IOException, UnsupportedCallbackException {
                for (javax.security.auth.callback.Callback c : callbacks) {
                    if (c instanceof PasswordCallback) {
                        ((PasswordCallback) c).setPassword(null);
                    }
                }
            }
        });
    } catch (Exception eiie) {
        Logger.getLogger().addEntry(eiie);
        throw new LibraryNotLoadedException(Bundle.getBundle().getString("libraryNotLoaded"));
    }

    Security.addProvider(pkcs11Provider);

    try {
        pkcs11ks = KeyStore.getInstance("PKCS11");
        pkcs11ks.load(null, null);
    } catch (Exception e) {
        Logger.getLogger().addEntry(e);
        throw new KeyStoreNotLoadedException(Bundle.getBundle().getString("keystoreNotLoaded"));
    }

    final Enumeration aliasesEnum = pkcs11ks.aliases();
    aliasList.clear();

    while (aliasesEnum.hasMoreElements()) {
        final String alias = (String) aliasesEnum.nextElement();
        if (null != alias) {
            if (alias.isEmpty()) {
                throw new AliasException(Bundle.getBundle().getString("blankAlias"));
            } else {
                final Certificate[] certChain = pkcs11ks.getCertificateChain(alias);
                if (null != certChain) {
                    if (CCAlias.ASSINATURA.equals(alias)) {
                        if (0 == certChain.length) {
                            throw new CertificateException(Bundle.getBundle().getString("chainInvalidFormat"));
                        } else {
                            final Certificate cert = certChain[0];
                            try {
                                ((X509Certificate) cert).checkValidity();
                                if (1 <= certChain.length) {
                                    final CCAlias ccAliasTemp = new CCAlias(alias, certChain);
                                    aliasList.add(ccAliasTemp);
                                }
                            } catch (CertificateExpiredException cee) {
                                Logger.getLogger().addEntry(cee);
                                throw new CertificateException(Bundle.getBundle().getString("aliasCertificate")
                                        + " " + alias + " " + Bundle.getBundle().getString("expired") + "!");
                            } catch (CertificateNotYetValidException cee) {
                                Logger.getLogger().addEntry(cee);
                                throw new CertificateException(
                                        Bundle.getBundle().getString("aliasCertificate") + " " + alias + " "
                                                + Bundle.getBundle().getString("notYetValid") + "!");
                            }
                        }
                    }
                }
            }
        }
    }
    return aliasList;
}