Search in sources :

Example 16 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler in project jdk8u_jdk by JetBrains.

the class RefreshKrb5Config method main.

public static void main(String[] args) throws LoginException, IOException {
    Map<String, String> principals = new HashMap<>();
    principals.put(USER_PRINCIPAL, USER_PASSWORD);
    principals.put(KRBTGT_PRINCIPAL, null);
    System.setProperty("java.security.krb5.conf", KRB5_CONF_FILENAME);
    // start a local KDC, and save krb5 config
    KDC kdc = KDC.startKDC(HOST, null, REALM, principals, null, null);
    KDC.saveConfig(KRB5_CONF_FILENAME, kdc, "max_retries = 1");
    System.setProperty("java.security.auth.login.config", TEST_SRC + File.separator + "refreshKrb5Config.jaas");
    CallbackHandler handler = new Helper.UserPasswordHandler(USER, USER_PASSWORD);
    // set incorrect KDC
    System.out.println("java.security.krb5.kdc = " + NOT_EXISTING_HOST);
    System.setProperty("java.security.krb5.kdc", NOT_EXISTING_HOST);
    System.out.println("java.security.krb5.realm = " + REALM);
    System.setProperty("java.security.krb5.realm", REALM);
    try {
        new LoginContext("Refreshable", handler).login();
        throw new RuntimeException("Expected exception not thrown");
    } catch (LoginException le) {
        System.out.println("Expected login failure: " + le);
    }
    // reset properties
    System.out.println("Reset java.security.krb5.kdc");
    System.clearProperty("java.security.krb5.kdc");
    System.out.println("Reset java.security.krb5.realm");
    System.clearProperty("java.security.krb5.realm");
    // login with not-refreshable config
    try {
        new LoginContext("NotRefreshable", handler).login();
        throw new RuntimeException("Expected exception not thrown");
    } catch (LoginException le) {
        System.out.println("Expected login failure: " + le);
    }
    // login with refreshable config
    new LoginContext("Refreshable", handler).login();
    System.out.println("Test passed");
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) LoginContext(javax.security.auth.login.LoginContext) HashMap(java.util.HashMap) LoginException(javax.security.auth.login.LoginException)

Example 17 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler in project alluxio by Alluxio.

the class PlainSaslClientCallbackHandlerTest method clientCallbackHandler.

/**
   * Tests that the callback is handled correctly.
   */
@Test
public void clientCallbackHandler() throws Exception {
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username:");
    callbacks[1] = new PasswordCallback("Password:", true);
    String user = "alluxio-user-1";
    String password = "alluxio-user-1-password";
    CallbackHandler clientCBHandler = new PlainSaslClientCallbackHandler(user, password);
    clientCBHandler.handle(callbacks);
    validateCallbacks(user, password, callbacks);
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) RealmCallback(javax.security.sasl.RealmCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) Test(org.junit.Test)

Example 18 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler in project alluxio by Alluxio.

the class PlainSaslClientCallbackHandlerTest method unsupportCallback.

/**
   * Tests that an exception is thrown in case an unsupported callback is used.
   */
@Test
public void unsupportCallback() throws Exception {
    mThrown.expect(UnsupportedCallbackException.class);
    mThrown.expectMessage(RealmCallback.class + " is unsupported.");
    Callback[] callbacks = new Callback[3];
    callbacks[0] = new NameCallback("Username:");
    callbacks[1] = new PasswordCallback("Password:", true);
    callbacks[2] = new RealmCallback("Realm:");
    String user = "alluxio-user-2";
    String password = "alluxio-user-2-password";
    CallbackHandler clientCBHandler = new PlainSaslClientCallbackHandler(user, password);
    clientCBHandler.handle(callbacks);
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) RealmCallback(javax.security.sasl.RealmCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) RealmCallback(javax.security.sasl.RealmCallback) Test(org.junit.Test)

Example 19 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler in project alluxio by Alluxio.

the class LoginUser method login.

/**
   * Logs in based on the LoginModules.
   *
   * @return the login user
   * @throws IOException if login fails
   */
private static User login() throws IOException {
    AuthType authType = Configuration.getEnum(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.class);
    checkSecurityEnabled(authType);
    Subject subject = new Subject();
    try {
        CallbackHandler callbackHandler = null;
        if (authType.equals(AuthType.SIMPLE) || authType.equals(AuthType.CUSTOM)) {
            callbackHandler = new AppLoginModule.AppCallbackHandler();
        }
        // Create LoginContext based on authType, corresponding LoginModule should be registered
        // under the authType name in LoginModuleConfiguration.
        LoginContext loginContext = new LoginContext(authType.getAuthName(), subject, callbackHandler, new LoginModuleConfiguration());
        loginContext.login();
    } catch (LoginException e) {
        throw new IOException("Failed to login: " + e.getMessage(), e);
    }
    Set<User> userSet = subject.getPrincipals(User.class);
    if (userSet.isEmpty()) {
        throw new IOException("Failed to login: No Alluxio User is found.");
    }
    if (userSet.size() > 1) {
        StringBuilder msg = new StringBuilder("Failed to login: More than one Alluxio Users are found:");
        for (User user : userSet) {
            msg.append(" ").append(user.toString());
        }
        throw new IOException(msg.toString());
    }
    return userSet.iterator().next();
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) LoginContext(javax.security.auth.login.LoginContext) LoginModuleConfiguration(alluxio.security.login.LoginModuleConfiguration) LoginException(javax.security.auth.login.LoginException) AuthType(alluxio.security.authentication.AuthType) IOException(java.io.IOException) Subject(javax.security.auth.Subject) AppLoginModule(alluxio.security.login.AppLoginModule)

Example 20 with CallbackHandler

use of javax.security.auth.callback.CallbackHandler in project ats-framework by Axway.

the class InetSmtpConnection method authenticate.

// -- Authentication --
/**
     * Authenticates the connection using the specified SASL mechanism,
     * username, and password.
     * @param mechanism a SASL authentication mechanism, e.g. LOGIN, PLAIN,
     * CRAM-MD5, GSSAPI
     * @param username the authentication principal
     * @param password the authentication credentials
     * @return true if authentication was successful, false otherwise
     */
public boolean authenticate(String mechanism, String username, String password) throws IOException {
    try {
        String[] m = new String[] { mechanism };
        CallbackHandler ch = new SaslCallbackHandler(username, password);
        // Avoid lengthy callback procedure for GNU Crypto
        HashMap<String, String> p = new HashMap<String, String>();
        p.put("gnu.crypto.sasl.username", username);
        p.put("gnu.crypto.sasl.password", password);
        SaslClient sasl = Sasl.createSaslClient(m, null, "smtp", socket.getInetAddress().getHostName(), p, ch);
        if (sasl == null) {
            // Fall back to home-grown SASL clients
            if ("LOGIN".equalsIgnoreCase(mechanism)) {
                sasl = new SaslLogin(username, password);
            } else if ("PLAIN".equalsIgnoreCase(mechanism)) {
                sasl = new SaslPlain(username, password);
            } else if ("CRAM-MD5".equalsIgnoreCase(mechanism)) {
                sasl = new SaslCramMD5(username, password);
            } else {
                return false;
            }
        }
        StringBuffer cmd = new StringBuffer(AUTH);
        cmd.append(' ');
        cmd.append(mechanism);
        if (sasl.hasInitialResponse()) {
            cmd.append(' ');
            byte[] init = sasl.evaluateChallenge(new byte[0]);
            if (init.length == 0) {
                cmd.append('=');
            } else {
                cmd.append(new String(BASE64.encode(init), "US-ASCII"));
            }
        }
        send(cmd.toString());
        while (true) {
            switch(getAllResponses()) {
                case 334:
                    try {
                        byte[] c0 = response.getBytes("US-ASCII");
                        // challenge
                        byte[] c1 = BASE64.decode(c0);
                        byte[] r0 = sasl.evaluateChallenge(c1);
                        // response
                        byte[] r1 = BASE64.encode(r0);
                        out.write(r1);
                        out.write(0x0d);
                        out.flush();
                        log.trace("> " + new String(r1, "US-ASCII"));
                    } catch (SaslException e) {
                        // Error in SASL challenge evaluation - cancel exchange
                        out.write(0x2a);
                        out.write(0x0d);
                        out.flush();
                        log.trace("> *");
                    }
                    break;
                case 235:
                    String qop = (String) sasl.getNegotiatedProperty(Sasl.QOP);
                    if ("auth-int".equalsIgnoreCase(qop) || "auth-conf".equalsIgnoreCase(qop)) {
                        InputStream is = socket.getInputStream();
                        is = new BufferedInputStream(is);
                        is = new SaslInputStream(sasl, is);
                        is = new CRLFInputStream(is);
                        in = new LineInputStream(is);
                        OutputStream os = socket.getOutputStream();
                        os = new BufferedOutputStream(os);
                        os = new SaslOutputStream(sasl, os);
                        out = new CRLFOutputStream(os);
                    }
                    return true;
                default:
                    return false;
            }
        }
    } catch (SaslException e) {
        log.error(e.getMessage(), e);
        // No provider for mechanism
        return false;
    } catch (RuntimeException e) {
        log.error(e.getMessage(), e);
        // No javax.security.sasl classes
        return false;
    }
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) SaslCallbackHandler(gnu.inet.util.SaslCallbackHandler) SaslInputStream(gnu.inet.util.SaslInputStream) HashMap(java.util.HashMap) CRLFInputStream(gnu.inet.util.CRLFInputStream) BufferedInputStream(java.io.BufferedInputStream) LineInputStream(gnu.inet.util.LineInputStream) SaslInputStream(gnu.inet.util.SaslInputStream) InputStream(java.io.InputStream) BufferedOutputStream(java.io.BufferedOutputStream) MessageOutputStream(gnu.inet.util.MessageOutputStream) OutputStream(java.io.OutputStream) SaslOutputStream(gnu.inet.util.SaslOutputStream) CRLFOutputStream(gnu.inet.util.CRLFOutputStream) SaslException(javax.security.sasl.SaslException) CRLFOutputStream(gnu.inet.util.CRLFOutputStream) SaslClient(javax.security.sasl.SaslClient) SaslPlain(gnu.inet.util.SaslPlain) SaslOutputStream(gnu.inet.util.SaslOutputStream) BufferedInputStream(java.io.BufferedInputStream) SaslCramMD5(gnu.inet.util.SaslCramMD5) SaslCallbackHandler(gnu.inet.util.SaslCallbackHandler) CRLFInputStream(gnu.inet.util.CRLFInputStream) LineInputStream(gnu.inet.util.LineInputStream) BufferedOutputStream(java.io.BufferedOutputStream) SaslLogin(gnu.inet.util.SaslLogin)

Aggregations

CallbackHandler (javax.security.auth.callback.CallbackHandler)89 IOException (java.io.IOException)38 Callback (javax.security.auth.callback.Callback)36 PasswordCallback (javax.security.auth.callback.PasswordCallback)30 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)27 HashMap (java.util.HashMap)25 Subject (javax.security.auth.Subject)24 NameCallback (javax.security.auth.callback.NameCallback)22 LoginContext (javax.security.auth.login.LoginContext)17 LoginException (javax.security.auth.login.LoginException)15 Test (org.junit.Test)15 Map (java.util.Map)10 URL (java.net.URL)8 RealmCallback (javax.security.sasl.RealmCallback)7 QName (javax.xml.namespace.QName)6 Service (javax.xml.ws.Service)6 WSS4JOutInterceptor (org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor)6 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)5 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)5 TokenValidatorResponse (org.apache.cxf.sts.token.validator.TokenValidatorResponse)5