Example usage for javax.security.auth.login Configuration setConfiguration

List of usage examples for javax.security.auth.login Configuration setConfiguration

Introduction

In this page you can find the example usage for javax.security.auth.login Configuration setConfiguration.

Prototype

public static void setConfiguration(Configuration configuration) 

Source Link

Document

Set the login Configuration .

Usage

From source file:org.apache.solr.cloud.TestSolrCloudWithKerberos.java

private void setupMiniKdc() throws Exception {
    System.setProperty("solr.jaas.debug", "true");
    String kdcDir = createTempDir() + File.separator + "minikdc";
    kdc = KerberosTestUtil.getKdc(new File(kdcDir));
    File keytabFile = new File(kdcDir, "keytabs");
    String solrServerPrincipal = "HTTP/127.0.0.1";
    String solrClientPrincipal = "solr";
    kdc.start();/*  ww  w  .j ava  2 s  . co m*/
    kdc.createPrincipal(keytabFile, solrServerPrincipal, solrClientPrincipal);

    String jaas = "SolrClient {\n" + " com.sun.security.auth.module.Krb5LoginModule required\n"
            + " useKeyTab=true\n" + " keyTab=\"" + keytabFile.getAbsolutePath() + "\"\n" + " storeKey=true\n"
            + " useTicketCache=false\n" + " doNotPrompt=true\n" + " debug=true\n" + " principal=\""
            + solrClientPrincipal + "\";\n" + "};";

    Configuration conf = new KerberosTestUtil.JaasConfiguration(solrClientPrincipal, keytabFile, "SolrClient");
    Configuration.setConfiguration(conf);

    String jaasFilePath = kdcDir + File.separator + "jaas-client.conf";
    FileUtils.write(new File(jaasFilePath), jaas);
    System.setProperty("java.security.auth.login.config", jaasFilePath);
    System.setProperty("solr.kerberos.jaas.appname", "SolrClient"); // Get this app name from the jaas file
    System.setProperty("solr.kerberos.cookie.domain", "127.0.0.1");
    System.setProperty("solr.kerberos.principal", solrServerPrincipal);
    System.setProperty("solr.kerberos.keytab", keytabFile.getAbsolutePath());
    // Extracts 127.0.0.1 from HTTP/127.0.0.1@EXAMPLE.COM
    System.setProperty("solr.kerberos.name.rules",
            "RULE:[1:$1@$0](.*EXAMPLE.COM)s/@.*//" + "\nRULE:[2:$2@$0](.*EXAMPLE.COM)s/@.*//" + "\nDEFAULT");

    // more debugging, if needed
    /*System.setProperty("sun.security.jgss.debug", "true");
    System.setProperty("sun.security.krb5.debug", "true");
    System.setProperty("sun.security.jgss.debug", "true");
    System.setProperty("java.security.debug", "logincontext,policy,scl,gssloginconfig");*/
}

From source file:org.apache.storm.security.auth.kerberos.KerberosSaslTransportPlugin.java

public TTransportFactory getServerTransportFactory() throws IOException {
    //create an authentication callback handler
    CallbackHandler server_callback_handler = new ServerCallbackHandler(login_conf, topoConf);

    //login our principal
    Subject subject = null;//from   ww  w. ja  va  2 s .  c o  m
    try {
        //specify a configuration object to be used
        Configuration.setConfiguration(login_conf);
        //now login
        Login login = new Login(AuthUtils.LOGIN_CONTEXT_SERVER, server_callback_handler);
        subject = login.getSubject();
        login.startThreadIfNeeded();
    } catch (LoginException ex) {
        LOG.error("Server failed to login in principal:" + ex, ex);
        throw new RuntimeException(ex);
    }

    //check the credential of our principal
    if (subject.getPrivateCredentials(KerberosTicket.class).isEmpty()) {
        throw new RuntimeException("Fail to verify user principal with section \""
                + AuthUtils.LOGIN_CONTEXT_SERVER + "\" in login configuration file " + login_conf);
    }

    String principal = AuthUtils.get(login_conf, AuthUtils.LOGIN_CONTEXT_SERVER, "principal");
    LOG.debug("principal:" + principal);
    KerberosName serviceKerberosName = new KerberosName(principal);
    String serviceName = serviceKerberosName.getServiceName();
    String hostName = serviceKerberosName.getHostName();
    Map<String, String> props = new TreeMap<String, String>();
    props.put(Sasl.QOP, "auth");
    props.put(Sasl.SERVER_AUTH, "false");

    //create a transport factory that will invoke our auth callback for digest
    TSaslServerTransport.Factory factory = new TSaslServerTransport.Factory();
    factory.addServerDefinition(KERBEROS, serviceName, hostName, props, server_callback_handler);

    //create a wrap transport factory so that we could apply user credential during connections
    TUGIAssumingTransportFactory wrapFactory = new TUGIAssumingTransportFactory(factory, subject);

    LOG.info("SASL GSSAPI transport factory will be used");
    return wrapFactory;
}

From source file:com.teklabs.throng.integration.ldap.Ldap.java

/**
 * Checks password using GSSAPI./*from w w  w .j a va2 s. co m*/
 *
 * @param principal principal
 * @param password  password
 * @return true, if principal can be authenticated with specified password
 */
private boolean checkPasswordUsingGssapi(String principal, String password) {
    // Use our custom configuration to avoid reliance on external config
    Configuration.setConfiguration(new Krb5LoginConfiguration());
    LoginContext lc;
    try {
        lc = new LoginContext(getClass().getName(), new CallbackHandlerImpl(principal, password));
        lc.login();
    } catch (LoginException e) {
        // Bad username:  Client not found in Kerberos database
        // Bad password:  Integrity check on decrypted field failed
        LdapHelper.LOG.debug("Password is not valid for principal: " + principal, e);
        return false;
    }
    try {
        lc.logout();
    } catch (LoginException e) {
        LdapHelper.LOG.warn("Logout fails", e);
    }
    return true;

}

From source file:com.jivesoftware.authHelper.customescheme.negotiate.CustomNegotiateScheme.java

/**
 * Init GSSContext for negotiation.//w  ww.  j  a  v a  2  s .  c  om
 *
 * @param server servername only (e.g: radar.it.su.se)
 */
protected void init(String server, UsernamePasswordCredentials credentials) throws GSSException {
    LOG.info("init " + server);

    // Create a callback handler
    Configuration.setConfiguration(null);
    CallbackHandler callbackHandler = new CustomNegotiateCallbackHandler(credentials.getUserName(),
            credentials.getPassword());
    PrivilegedExceptionAction action = new MyAction(server);
    LoginContext con = null;

    try {
        CustomConfiguration cc = getCustomConfiguration(credentials);

        // Create a LoginContext with a callback handler
        con = new LoginContext("com.sun.security.jgss.login", null, callbackHandler, cc);

        Configuration.setConfiguration(cc);
        // Perform authentication
        con.login();
    } catch (LoginException e) {
        System.err.println("Login failed");
        e.printStackTrace();
        // System.exit(-1);
        throw new RuntimeException(e);
    } catch (Exception e) {
        System.err.println("Login failed");
        e.printStackTrace();
        // System.exit(-1);
        throw new RuntimeException(e);
    }

    // Perform action as authenticated user
    Subject subject = con.getSubject();
    //LOG.trace("Subject is :"+ subject.toString());

    LOG.info("Authenticated principal:**** " + subject.getPrincipals());

    try {
        Subject.doAs(subject, action);
    } catch (PrivilegedActionException e) {
        e.printStackTrace();

    } catch (Exception e) {
        e.printStackTrace();

    }

}

From source file:io.reappt.adapters.kafka.KafkaAdapter.java

public KafkaAdapter() throws NoSuchAlgorithmException, KeyManagementException {
    parseVcapServices(System.getenv("VCAP_SERVICES"));
    // Kafka or message hub insists that this property is set, even though we ignore it
    System.setProperty("java.security.auth.login.config", "make_kafka_happy");
    // Install our own Configuration implementation
    final Map<String, String> options = new HashMap<>();
    options.put("serviceName", "kafka");
    options.put("username", user);
    options.put("password", password);

    Configuration.setConfiguration(new Configuration() {
        @Override//from ww w .  ja v a2  s  .c  o m
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            return new AppConfigurationEntry[] {
                    new AppConfigurationEntry("com.ibm.messagehub.login.MessageHubLoginModule",
                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options) };
        }
    });

    this.session = createSession(this.reapptUrl, this.reapptUser, this.reapptPassword);

    serverTopicPartition = KAFKA_DIFFUSION_TOPIC + "-" + reapptUrl.hashCode();

    this.producer = new OutboundKafkaAdapter(session, bootstrap, serverTopicPartition);
    this.consumer = new InboundKafkaAdapter(session, bootstrap);
}

From source file:org.sonar.plugins.ldap.LdapAuthenticator.java

private boolean checkPasswordUsingGssapi(String principal, String password, String ldapKey) {
    // Use our custom configuration to avoid reliance on external config
    Configuration.setConfiguration(new Krb5LoginConfiguration());
    LoginContext lc;/*www . j ava  2 s.  c om*/
    try {
        lc = new LoginContext(getClass().getName(), new CallbackHandlerImpl(principal, password));
        lc.login();
    } catch (LoginException e) {
        // Bad username: Client not found in Kerberos database
        // Bad password: Integrity check on decrypted field failed
        LOG.debug("Password not valid for {} in server {}: {}", principal, ldapKey, e.getMessage());
        return false;
    }
    try {
        lc.logout();
    } catch (LoginException e) {
        LOG.warn("Logout fails", e);
    }
    return true;
}

From source file:org.jboss.test.kerberos.gss.GSSTestServer.java

/**
 * Authenticates this server in Kerberos KDC.
 * // w w w.j a  v  a2 s.  co  m
 * @throws LoginException
 * @throws PrivilegedActionException
 */
private void start() throws LoginException, PrivilegedActionException {
    System.out.println("Starting GSSTestServer - login");
    // Use our custom configuration to avoid reliance on external config
    Configuration.setConfiguration(new Configuration() {
        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            final Map<String, Object> options = new HashMap<String, Object>();
            options.put("refreshKrb5Config", "true");
            options.put("storeKey", "true");
            return new AppConfigurationEntry[] {
                    new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options) };
        }
    });
    // 1. Authenticate to Kerberos.
    final LoginContext lc = new LoginContext("foo",
            new UsernamePasswordHandler(PRINCIPAL, PASSWORD != null ? PASSWORD.toCharArray() : null));
    lc.login();
    System.out.println("Authentication succeed");
    // 2. Perform the work as authenticated Subject.
    final String finishMsg = Subject.doAs(lc.getSubject(), new ServerAction());
    System.out.println("Server stopped with result: " + (finishMsg == null ? "OK" : finishMsg));
    lc.logout();

}

From source file:org.marketcetera.saclient.MockStrategyAgent.java

/**
 * Sets up the JAAS Configuration such that both Client's test Mock server
 * and remote-receiver's can work.//from w  ww.  j  a v a2 s. co  m
 */
private static void setupConfiguration() {
    Configuration.setConfiguration(new Configuration() {
        public AppConfigurationEntry[] getAppConfigurationEntry(String inName) {
            if ("remoting-amq-domain".equals(inName)) {
                //the login module for the receiver module.
                return new AppConfigurationEntry[] {
                        new AppConfigurationEntry(ClientLoginModule.class.getName(),
                                AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
                                Collections.unmodifiableMap(new HashMap<String, String>())) };
            } else if ("test-amq-domain".equals(inName)) {
                //the login module for mock server
                return new AppConfigurationEntry[] { new AppConfigurationEntry(MockLoginModule.class.getName(),
                        AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
                        Collections.unmodifiableMap(new HashMap<String, String>())) };
            }
            return null;
        }
    });
}

From source file:io.confluent.rest.SaslTest.java

@After
public void cleanup() throws Exception {
    Configuration.setConfiguration(null);
    if (previousAuthConfig != null) {
        System.setProperty("java.security.auth.login.config", previousAuthConfig);
    }/*  w w  w.ja  va2s  .c om*/
    httpclient.close();
    app.stop();
}