Example usage for javax.security.auth.login LoginContext LoginContext

List of usage examples for javax.security.auth.login LoginContext LoginContext

Introduction

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

Prototype

public LoginContext(String name, Subject subject, CallbackHandler callbackHandler, Configuration config)
        throws LoginException 

Source Link

Document

Instantiate a new LoginContext object with a name, a Subject to be authenticated, a CallbackHandler object, and a login Configuration .

Usage

From source file:com.redhat.tools.kerberos.SunJaasKerberosClient.java

public String login(String username, String password) {
    LOG.debug("Trying to authenticate " + username + " with Kerberos");
    String validatedUsername = "";

    try {/*  www. j a  v a2 s.  c  o m*/
        LoginContext loginContext = new LoginContext("", null,
                new KerberosClientCallbackHandler(username, password), new LoginConfig(this.debug));
        loginContext.login();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Kerberos authenticated user: " + loginContext.getSubject());
        }
        validatedUsername = loginContext.getSubject().getPrincipals().iterator().next().toString();
        loginContext.logout();
    } catch (LoginException e) {
        e.printStackTrace();
    }
    return validatedUsername;

}

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//  w  w w . j a  v  a 2s . 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:org.apache.nifi.hadoop.KerberosKeytabSPNegoScheme.java

@Override
public byte[] generateToken(byte[] input, String authServer, Credentials credentials) {
    Set<Principal> principals = new HashSet<>();
    principals.add(credentials.getUserPrincipal());
    Subject subject = new Subject(false, principals, new HashSet<>(), new HashSet<>());

    try {/*from  w  ww. j  a va2 s.co  m*/
        LoginContext loginContext = new LoginContext("", subject, null,
                new KerberosConfiguration(credentials.getUserPrincipal().getName(),
                        ((KerberosKeytabCredentials) credentials).getKeytab()));
        loginContext.login();
        Subject loggedInSubject = loginContext.getSubject();

        return Subject.doAs(loggedInSubject, new PrivilegedExceptionAction<byte[]>() {

            public byte[] run() throws UnknownHostException, ClassNotFoundException, GSSException,
                    IllegalAccessException, NoSuchFieldException {
                GSSManager gssManager = GSSManager.getInstance();
                String servicePrincipal = KerberosUtil.getServicePrincipal("HTTP", authServer);
                Oid serviceOid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                GSSName serviceName = gssManager.createName(servicePrincipal, serviceOid);
                Oid mechOid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                GSSContext gssContext = gssManager.createContext(serviceName, mechOid, null, 0);
                gssContext.requestCredDeleg(true);
                gssContext.requestMutualAuth(true);
                return gssContext.initSecContext(input, 0, input.length);
            }

        });
    } catch (PrivilegedActionException | LoginException e) {
        throw new RuntimeException(e);
    }
}

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 w w  . ja va 2 s  .  co  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:com.qut.middleware.esoe.authn.plugins.spnego.authenticator.KerberosV5Authenticator.java

@SuppressWarnings("unchecked")
private String loginAndAction(String loginContextName, KerberosAuthenticationAction actionToPerform) {
    LoginContext context = null;/*from   w  ww.j  a  v a2  s  .  c  om*/

    try {
        // Create a LoginContext 
        context = new LoginContext(loginContextName, null, null, this.config);

        this.logger.trace(Messages.getString("KerberosV5Authenticator.7") + loginContextName); //$NON-NLS-1$

        // Perform server authentication
        context.login();

        Subject subject = context.getSubject();
        this.logger.trace(subject.toString());
        this.logger.trace(Messages.getString("KerberosV5Authenticator.8") + subject.getPrincipals()); //$NON-NLS-1$

        // perform kerberos validation
        return (String) (Subject.doAs(subject, actionToPerform));

    } catch (LoginException e) {
        this.logger.warn(Messages.getString("KerberosV5Authenticator.9")); //$NON-NLS-1$
        this.logger.trace(e.getLocalizedMessage(), e);

        return null;
    } catch (PrivilegedActionException e) {
        this.logger.trace(e.getLocalizedMessage(), e);
        this.logger.trace(Messages.getString("KerberosV5Authenticator.10") + e.getCause().getMessage()); //$NON-NLS-1$

        return null;
    } catch (Exception e) {
        this.logger.debug(Messages.getString("KerberosV5Authenticator.11") + e.getCause().getMessage()); //$NON-NLS-1$
        this.logger.trace(e.getLocalizedMessage(), e);

        return null;
    }

}

From source file:io.druid.security.kerberos.DruidKerberosAuthenticationHandler.java

@Override
public void init(Properties config) throws ServletException {
    try {// w w w . ja  va2s  .c o m
        String principal = config.getProperty(PRINCIPAL);
        if (principal == null || principal.trim().length() == 0) {
            throw new ServletException("Principal not defined in configuration");
        }
        keytab = config.getProperty(KEYTAB, keytab);
        if (keytab == null || keytab.trim().length() == 0) {
            throw new ServletException("Keytab not defined in configuration");
        }
        if (!new File(keytab).exists()) {
            throw new ServletException("Keytab does not exist: " + keytab);
        }

        // use all SPNEGO principals in the keytab if a principal isn't
        // specifically configured
        final String[] spnegoPrincipals;
        if (principal.equals("*")) {
            spnegoPrincipals = KerberosUtil.getPrincipalNames(keytab, Pattern.compile("HTTP/.*"));
            if (spnegoPrincipals.length == 0) {
                throw new ServletException("Principals do not exist in the keytab");
            }
        } else {
            spnegoPrincipals = new String[] { principal };
        }

        String nameRules = config.getProperty(NAME_RULES, null);
        if (nameRules != null) {
            KerberosName.setRules(nameRules);
        }

        for (String spnegoPrincipal : spnegoPrincipals) {
            log.info("Login using keytab %s, for principal %s", keytab, spnegoPrincipal);
            final KerberosAuthenticator.DruidKerberosConfiguration kerberosConfiguration = new KerberosAuthenticator.DruidKerberosConfiguration(
                    keytab, spnegoPrincipal);
            final LoginContext loginContext = new LoginContext("", serverSubject, null, kerberosConfiguration);
            try {
                loginContext.login();
            } catch (LoginException le) {
                log.warn(le, "Failed to login as [%s]", spnegoPrincipal);
                throw new AuthenticationException(le);
            }
            loginContexts.add(loginContext);
        }
        try {
            gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() {

                @Override
                public GSSManager run() throws Exception {
                    return GSSManager.getInstance();
                }
            });
        } catch (PrivilegedActionException ex) {
            throw ex.getException();
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

From source file:com.salesmanager.core.module.impl.application.logon.CustomerJAASLogonImpl.java

private boolean isValidLogin(HttpServletRequest req, String username, String password, int merchantId) {
    LoginContext context = null;/*from  w  w w. j  a va2s.c  o m*/
    try {

        // 1) using jaas.conf
        // context = new LoginContext(LOGIN_CONTEXT_CONFIG_NAME,new
        // CustomerLoginCallBackHandler(username,password));

        // 2) programaticaly created jaas.conf equivalent
        SalesManagerJAASConfiguration jaasc = new SalesManagerJAASConfiguration(
                "com.salesmanager.core.module.impl.application.logon.JAASSecurityCustomerLoginModule");
        context = new LoginContext(LOGIN_CONTEXT_CONFIG_NAME, null,
                new CustomerLoginCallBackHandler(username, password, merchantId), jaasc);

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Unable to Create Login Context, configuration file may be missing", e);
        /**
         * needs a jaas.conf file in the startup script Logon {
         * com.salesmanager.core.module.impl.application.logon.
         * JAASSecurityCustomerLoginModule required; }; and this parameter
         * -Djava.security.auth.login.config=jaas.conf
         */
    }
    if (context != null) {
        try {
            context.login();

            Subject s = context.getSubject();

            if (s != null) {
                Set principals = s.getPrincipals();
            }

            // Create a principal
            UserPrincipal principal = new UserPrincipal(username);

            HttpSession session = req.getSession();
            session.setAttribute("PRINCIPAL", principal);
            session.setAttribute("LOGINCONTEXT", context);

            return true;
        } catch (LoginException e) {
            e.printStackTrace();
            return false;
        }
    }
    return false;
}

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

/**
 * Init GSSContext for negotiation.//from w  w w. j  a  v  a 2 s  . c  o m
 *
 * @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:com.redhat.tools.kerberos.SunJaasKerberosTicketValidator.java

public void setProperties() throws Exception {
    // if (keyTabLocation instanceof ClassPathResource) {
    // LOG.warn("Your keytab is in the classpath. This file needs special protection and shouldn't be in the classpath. JAAS may also not be able to load this file from classpath.");
    // }//from  ww w.  j  a v  a2 s. co  m
    URL keytabURL = new URL(this.keyTabLocation);
    LoginConfig loginConfig = new LoginConfig(keytabURL.toExternalForm(), this.servicePrincipal, this.debug);
    Set<Principal> princ = new HashSet<Principal>(1);
    princ.add(new KerberosPrincipal(this.servicePrincipal));
    Subject sub = new Subject(false, princ, new HashSet<Object>(), new HashSet<Object>());
    LoginContext lc = new LoginContext("", sub, null, loginConfig);
    lc.login();
    this.serviceSubject = lc.getSubject();
}

From source file:com.cloudera.alfredo.server.KerberosAuthenticationHandler.java

/**
 * Initializes the authentication handler instance.
 * <p/>// w w  w  . jav  a2s  .  com
 * It creates a Kerberos context using the principal and keytab specified in the configuration.
 * <p/>
 * This method is invoked by the {@link AuthenticationFilter#init} method.
 *
 * @param config configuration properties to initialize the handler.
 *
 * @throws ServletException thrown if the handler could not be initialized.
 */
@Override
public void init(Properties config) throws ServletException {
    try {
        principal = config.getProperty(PRINCIPAL, principal);
        if (principal == null || principal.trim().length() == 0) {
            throw new ServletException("Principal not defined in configuration");
        }
        keytab = config.getProperty(KEYTAB, keytab);
        if (keytab == null || keytab.trim().length() == 0) {
            throw new ServletException("Keytab not defined in configuration");
        }
        if (!new File(keytab).exists()) {
            throw new ServletException("Keytab does not exist: " + keytab);
        }

        Set<Principal> principals = new HashSet<Principal>();
        principals.add(new KerberosPrincipal(principal));
        Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());

        KerberosConfiguration kerberosConfiguration = new KerberosConfiguration(keytab, principal);

        loginContext = new LoginContext("", subject, null, kerberosConfiguration);
        loginContext.login();

        Subject serverSubject = loginContext.getSubject();
        try {
            gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() {

                @Override
                public GSSManager run() throws Exception {
                    return GSSManager.getInstance();
                }
            });
        } catch (PrivilegedActionException ex) {
            throw ex.getException();
        }
        LOG.info("Initialized, principal [{}] from keytab [{}]", principal, keytab);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}