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

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

Introduction

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

Prototype

public void login() throws LoginException 

Source Link

Document

Perform the authentication.

Usage

From source file:com.buaa.cfs.security.UserGroupInformation.java

/**
 * Create a UserGroupInformation from a Kerberos ticket cache.
 *
 * @param user The principal name to load from the ticket cache
 *
 * @throws IOException if the kerberos login fails
 *//*www .j  a  va2  s . c  om*/

public static UserGroupInformation getUGIFromTicketCache(String ticketCache, String user) throws IOException {
    if (!isAuthenticationMethodEnabled(AuthenticationMethod.KERBEROS)) {
        return getBestUGI(null, user);
    }
    try {
        Map<String, String> krbOptions = new HashMap<String, String>();
        if (IBM_JAVA) {
            krbOptions.put("useDefaultCcache", "true");
            // The first value searched when "useDefaultCcache" is used.
            System.setProperty("KRB5CCNAME", ticketCache);
        } else {
            krbOptions.put("doNotPrompt", "true");
            krbOptions.put("useTicketCache", "true");
            krbOptions.put("useKeyTab", "false");
            krbOptions.put("ticketCache", ticketCache);
        }
        krbOptions.put("renewTGT", "false");
        krbOptions.putAll(HadoopConfiguration.BASIC_JAAS_OPTIONS);
        AppConfigurationEntry ace = new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(),
                LoginModuleControlFlag.REQUIRED, krbOptions);
        DynamicConfiguration dynConf = new DynamicConfiguration(new AppConfigurationEntry[] { ace });
        LoginContext login = newLoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, null, dynConf);
        login.login();

        Subject loginSubject = login.getSubject();
        Set<Principal> loginPrincipals = loginSubject.getPrincipals();
        if (loginPrincipals.isEmpty()) {
            throw new RuntimeException("No login principals found!");
        }
        if (loginPrincipals.size() != 1) {
            LOG.warn("found more than one principal in the ticket cache file " + ticketCache);
        }
        User ugiUser = new User(loginPrincipals.iterator().next().getName(), AuthenticationMethod.KERBEROS,
                login);
        loginSubject.getPrincipals().add(ugiUser);
        UserGroupInformation ugi = new UserGroupInformation(loginSubject);
        ugi.setLogin(login);
        ugi.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
        return ugi;
    } catch (LoginException le) {
        throw new IOException("failure to login using ticket cache file " + ticketCache, le);
    }
}

From source file:com.xebialabs.overthere.cifs.winrm.WinRmClient.java

/**
 * Performs the JAAS login and run the sendRequest method within a privileged scope.
 *///from   w w w. j  a va 2  s  .  co  m
private Document runPrivileged(final PrivilegedSendMessage privilegedSendMessage) {
    final CallbackHandler handler = new ProvidedAuthCallback(username, password);
    Document result;
    try {
        final LoginContext lc = new LoginContext("", null, handler,
                new KerberosJaasConfiguration(kerberosDebug));
        lc.login();

        result = Subject.doAs(lc.getSubject(), privilegedSendMessage);
    } catch (LoginException e) {
        throw new WinRmRuntimeIOException(
                "Login failure sending message on " + targetURL + " error: " + e.getMessage(),
                privilegedSendMessage.getRequestDocument(), null, e);
    } catch (PrivilegedActionException e) {
        throw new WinRmRuntimeIOException(
                "Failure sending message on " + targetURL + " error: " + e.getMessage(),
                privilegedSendMessage.getRequestDocument(), null, e.getException());
    }
    return result;
}

From source file:com.buaa.cfs.security.UserGroupInformation.java

/**
 * Log in a user using the given subject
 *
 * @throws IOException if login fails/*from  w  w  w . jav a2  s  .  co m*/
 * @parma subject the subject to use when logging in a user, or null to create a new subject.
 */

public synchronized static void loginUserFromSubject(Subject subject) throws IOException {
    ensureInitialized();
    try {
        if (subject == null) {
            subject = new Subject();
        }
        LoginContext login = newLoginContext(authenticationMethod.getLoginAppName(), subject,
                new HadoopConfiguration());
        login.login();
        UserGroupInformation realUser = new UserGroupInformation(subject);
        realUser.setLogin(login);
        realUser.setAuthenticationMethod(authenticationMethod);
        realUser = new UserGroupInformation(login.getSubject());
        // If the HADOOP_PROXY_USER environment variable or property
        // is specified, create a proxy user as the logged in user.
        String proxyUser = System.getenv(HADOOP_PROXY_USER);
        if (proxyUser == null) {
            proxyUser = System.getProperty(HADOOP_PROXY_USER);
        }
        loginUser = proxyUser == null ? realUser : createProxyUser(proxyUser, realUser);

        String fileLocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION);
        if (fileLocation != null) {
            // Load the token storage file and put all of the tokens into the
            // user. Don't use the FileSystem API for reading since it has a lock
            // cycle (HADOOP-9212).
            //                Credentials cred = Credentials.readTokenStorageFile(
            //                        new File(fileLocation), conf);
            //                loginUser.addCredentials(cred);
        }
        loginUser.spawnAutoRenewalThreadForUserCreds();
    } catch (LoginException le) {
        LOG.debug("failure to login", le);
        throw new IOException("failure to login", le);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("UGI loginUser:" + loginUser);
    }
}

From source file:br.mdarte.exemplo.academico.accessControl.LoginController.java

public final boolean verificarLogin(ActionMapping mapping, VerificarLoginForm form, HttpServletRequest request,
        HttpServletResponse response, HttpServlet servlet) throws Exception {
    EntrarLoginValidarFormImpl formLogin = null;
    String login = null;/*from   w  ww.jav  a  2 s . c  om*/
    String senha = null;
    try {
        formLogin = (EntrarLoginValidarFormImpl) form;
        login = formLogin.getLogin();
        senha = formLogin.getSenha();
    } catch (Exception e) {
        senha = request.getParameter(ATTR_SENHA);
        login = request.getParameter(ATTR_LOGIN);
    }
    LoginContext loginCtx = null;
    ControleAcesso controleAcesso = new ControleAcessoImpl();
    try {
        if (controleAcesso.usuarioBloqueado(login)) {
            saveErrorMessage(request, "usuario.bloqueado");
            return false;
        }
        CallbackHandler handler = new LoginCallbackHandler(login, senha);
        loginCtx = new LoginContext("sistemaacademico", handler);
        loginCtx.login();
        Subject subject = loginCtx.getSubject();
        accessControl.SecurityHolder.setSubject(subject);
        PrincipalImpl principal = ControleAcesso.getCallerPrincipal(subject);
        principal.setNomeProjeto("sistemaacademico");
        request.getSession().setAttribute(Constantes.USER_SESSION, subject);
        String nome = principal.getOperador().getNomeIdentificadorMenu();
        request.getSession().setAttribute("nomeIdentificadorMenu", nome);
        posLogin(principal.getOperador(), request);
        return true;
    } catch (LoginException le) {
        if (le.getMessage().equals("Password Incorrect/Password Required")) {
            saveErrorMessage(request, "senha.incorreta");
        } else if (le.getMessage().equals("No matching username found in Principals")) {
            saveErrorMessage(request, "usuario.incorreto");
        } else {
            saveErrorMessage(request, le.getMessage());
        }
        return false;
    }
}

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

/**
 * Init GSSContext for negotiation./*from   w ww .  java  2  s. co 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.buaa.cfs.security.UserGroupInformation.java

/**
 * Log a user in from a keytab file. Loads a user identity from a keytab file and login them in. This new user does
 * not affect the currently logged-in user.
 *
 * @param user the principal name to load from the keytab
 * @param path the path to the keytab file
 *
 * @throws IOException if the keytab file can't be read
 *//*from   www  . j  a  v a2  s .  c  o m*/
public synchronized static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user, String path)
        throws IOException {
    if (!isSecurityEnabled())
        return UserGroupInformation.getCurrentUser();
    String oldKeytabFile = null;
    String oldKeytabPrincipal = null;

    long start = 0;
    try {
        oldKeytabFile = keytabFile;
        oldKeytabPrincipal = keytabPrincipal;
        keytabFile = path;
        keytabPrincipal = user;
        Subject subject = new Subject();

        LoginContext login = newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject,
                new HadoopConfiguration());

        start = Time.now();
        login.login();
        //            metrics.loginSuccess.add(Time.now() - start);
        UserGroupInformation newLoginUser = new UserGroupInformation(subject);
        newLoginUser.setLogin(login);
        newLoginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS);

        return newLoginUser;
    } catch (LoginException le) {
        if (start > 0) {
            //                metrics.loginFailure.add(Time.now() - start);
        }
        throw new IOException("Login failure for " + user + " from keytab " + path, le);
    } finally {
        if (oldKeytabFile != null)
            keytabFile = oldKeytabFile;
        if (oldKeytabPrincipal != null)
            keytabPrincipal = oldKeytabPrincipal;
    }
}

From source file:com.xebialabs.overthere.winrm.WinRmClient.java

/**
 * Performs the JAAS login and run the sendRequest method within a privileged scope.
 *//*from ww w  .  j a  va 2 s  .  c o  m*/
private Document runPrivileged(final PrivilegedSendMessage privilegedSendMessage) {
    final CallbackHandler handler = new ProvidedAuthCallback(username, password);
    Document result;
    try {
        final LoginContext lc = new LoginContext("", null, handler,
                new KerberosJaasConfiguration(kerberosDebug, kerberosTicketCache));
        lc.login();

        result = Subject.doAs(lc.getSubject(), privilegedSendMessage);
    } catch (LoginException e) {
        throw new WinRmRuntimeIOException(
                "Login failure sending message on " + targetURL + " error: " + e.getMessage(),
                privilegedSendMessage.getRequestDocument(), null, e);
    } catch (PrivilegedActionException e) {
        throw new WinRmRuntimeIOException(
                "Failure sending message on " + targetURL + " error: " + e.getMessage(),
                privilegedSendMessage.getRequestDocument(), null, e.getException());
    }
    return result;
}

From source file:com.adito.activedirectory.ActiveDirectoryUserDatabaseConfiguration.java

LoginContext createLoginContext(String username, String password) throws LoginException {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating login context for " + username);
    }/*from ww  w  .j  ava  2s  .  co  m*/

    UserPasswordCallbackHandler callbackHandler = new UserPasswordCallbackHandler();
    callbackHandler.setUserId(username);
    callbackHandler.setPassword(password);

    LoginContext context = new LoginContext(ActiveDirectoryUserDatabase.class.getName(), callbackHandler);
    context.login();
    return context;
}

From source file:com.buaa.cfs.security.UserGroupInformation.java

/**
 * Log a user in from a keytab file. Loads a user identity from a keytab file and logs them in. They become the
 * currently logged-in user.//  w  ww  .j av a  2s.c  o m
 *
 * @param user the principal name to load from the keytab
 * @param path the path to the keytab file
 *
 * @throws IOException if the keytab file can't be read
 */

public synchronized static void loginUserFromKeytab(String user, String path) throws IOException {
    if (!isSecurityEnabled())
        return;

    keytabFile = path;
    keytabPrincipal = user;
    Subject subject = new Subject();
    LoginContext login;
    long start = 0;
    try {
        login = newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject,
                new HadoopConfiguration());
        start = Time.now();
        login.login();
        //            metrics.loginSuccess.add(Time.now() - start);
        loginUser = new UserGroupInformation(subject);
        loginUser.setLogin(login);
        loginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
    } catch (LoginException le) {
        if (start > 0) {
            //                metrics.loginFailure.add(Time.now() - start);
        }
        throw new IOException("Login failure for " + user + " from keytab " + path + ": " + le, le);
    }
    LOG.info("Login successful for user " + keytabPrincipal + " using keytab file " + keytabFile);
}