Java Code Examples for javax.security.auth.login.LoginContext#logout()

The following examples show how to use javax.security.auth.login.LoginContext#logout() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KerberosAuthenticationManagerTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private AuthenticationResult authenticate(final SaslNegotiator negotiator) throws Exception
{
    final LoginContext lc = UTILS.createKerberosKeyTabLoginContext(getTestName(),
                                                                   CLIENT_PRINCIPAL_FULL_NAME,
                                                                   _clientKeyTabFile);

    Subject clientSubject = null;
    try
    {
        lc.login();
        clientSubject = lc.getSubject();
        debug("LoginContext subject {}", clientSubject);
        final SaslClient saslClient = createSaslClient(clientSubject);
        return performNegotiation(clientSubject, saslClient, negotiator);
    }
    finally
    {
        if (clientSubject != null)
        {
            lc.logout();
        }
    }
}
 
Example 2
Source File: TestKMS.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private <T> T doAs(String user, final PrivilegedExceptionAction<T> action)
    throws Exception {
  Set<Principal> principals = new HashSet<Principal>();
  principals.add(new KerberosPrincipal(user));

  //client login
  Subject subject = new Subject(false, principals,
      new HashSet<Object>(), new HashSet<Object>());
  LoginContext loginContext = new LoginContext("", subject, null,
      KerberosConfiguration.createClientConfig(user, keytab));
  try {
    loginContext.login();
    subject = loginContext.getSubject();
    UserGroupInformation ugi =
        UserGroupInformation.getUGIFromSubject(subject);
    return ugi.doAs(action);
  } finally {
    loginContext.logout();
  }
}
 
Example 3
Source File: TestSecureLogins.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientLogin() throws Throwable {
  LoginContext client = login(ALICE_LOCALHOST,
                              ALICE_CLIENT_CONTEXT,
                              keytab_alice);

  try {
    logLoginDetails(ALICE_LOCALHOST, client);
    String confFilename = System.getProperty(Environment.JAAS_CONF_KEY);
    assertNotNull("Unset: "+ Environment.JAAS_CONF_KEY, confFilename);
    String config = FileUtils.readFileToString(new File(confFilename));
    LOG.info("{}=\n{}", confFilename, config);
    RegistrySecurity.setZKSaslClientProperties(ALICE, ALICE_CLIENT_CONTEXT);
  } finally {
    client.logout();
  }
}
 
Example 4
Source File: LCTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    if (args.length < 2) {
        throw new RuntimeException("Incorrect test params");
    }
    String nameOfContext = args[0];
    boolean isPositive = Boolean.parseBoolean(args[1]);
    String actionName = null;
    if (args.length == 3) {
        actionName = args[2];
    }
    try {
        LoginContext lc = new LoginContext(nameOfContext,
                new MyCallbackHandler());
        lc.login();
        checkPrincipal(lc, true);
        lc.logout();
        checkPrincipal(lc, false);
        if (!isPositive) {
            throw new RuntimeException("Test failed. Exception expected.");
        }
    } catch (LoginException le) {
        if (isPositive) {
            throw new RuntimeException("Test failed. Unexpected " +
                    "exception", le);
        }
        System.out.println("Expected exception: "
                + le.getMessage());
    }
    checkActions(actionName);
    System.out.println("Test passed.");
}
 
Example 5
Source File: LCTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    if (args.length < 2) {
        throw new RuntimeException("Incorrect test params");
    }
    String nameOfContext = args[0];
    boolean isPositive = Boolean.parseBoolean(args[1]);
    String actionName = null;
    if (args.length == 3) {
        actionName = args[2];
    }
    try {
        LoginContext lc = new LoginContext(nameOfContext,
                new MyCallbackHandler());
        lc.login();
        checkPrincipal(lc, true);
        lc.logout();
        checkPrincipal(lc, false);
        if (!isPositive) {
            throw new RuntimeException("Test failed. Exception expected.");
        }
    } catch (LoginException le) {
        if (isPositive) {
            throw new RuntimeException("Test failed. Unexpected " +
                    "exception", le);
        }
        System.out.println("Expected exception: "
                + le.getMessage());
    }
    checkActions(actionName);
    System.out.println("Test passed.");
}
 
Example 6
Source File: RegistryTestHelper.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * log out from a context if non-null ... exceptions are caught and logged
 * @param login login context
 * @return null, always
 */
public static LoginContext logout(LoginContext login) {
  try {
    if (login != null) {
      LOG.debug("Logging out login context {}", login.toString());
      login.logout();
    }
  } catch (LoginException e) {
    LOG.warn("Exception logging out: {}", e, e);
  }
  return null;
}
 
Example 7
Source File: TestUserGroupInformation.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test (timeout = 30000)
public void testLoginModuleCommit() throws Exception {
  UserGroupInformation loginUgi = UserGroupInformation.getLoginUser();
  User user1 = loginUgi.getSubject().getPrincipals(User.class).iterator()
      .next();
  LoginContext login = user1.getLogin();
  login.logout();
  login.login();
  User user2 = loginUgi.getSubject().getPrincipals(User.class).iterator()
      .next();
  // user1 and user2 must be same instances.
  Assert.assertTrue(user1 == user2);
}
 
Example 8
Source File: LCTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    if (args.length < 2) {
        throw new RuntimeException("Incorrect test params");
    }
    String nameOfContext = args[0];
    boolean isPositive = Boolean.parseBoolean(args[1]);
    String actionName = null;
    if (args.length == 3) {
        actionName = args[2];
    }
    try {
        LoginContext lc = new LoginContext(nameOfContext,
                new MyCallbackHandler());
        lc.login();
        checkPrincipal(lc, true);
        lc.logout();
        checkPrincipal(lc, false);
        if (!isPositive) {
            throw new RuntimeException("Test failed. Exception expected.");
        }
    } catch (LoginException le) {
        if (isPositive) {
            throw new RuntimeException("Test failed. Unexpected " +
                    "exception", le);
        }
        System.out.println("Expected exception: "
                + le.getMessage());
    }
    checkActions(actionName);
    System.out.println("Test passed.");
}
 
Example 9
Source File: JaasAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws GeneralSecurityException, PreventedException {

    if (this.kerberosKdcSystemProperty != null) {
        logger.debug("Setting kerberos system property {} to {}", SYS_PROP_KERB5_KDC, this.kerberosKdcSystemProperty);
        System.setProperty(SYS_PROP_KERB5_KDC, this.kerberosKdcSystemProperty);
    }
    if (this.kerberosRealmSystemProperty != null) {
        logger.debug("Setting kerberos system property {} to {}", SYS_PROP_KRB5_REALM, this.kerberosRealmSystemProperty);
        System.setProperty(SYS_PROP_KRB5_REALM, this.kerberosRealmSystemProperty);
    }
    
    final String username = credential.getUsername();
    final String password = getPasswordEncoder().encode(credential.getPassword());
    final LoginContext lc = new LoginContext(
            this.realm,
            new UsernamePasswordCallbackHandler(username, password));
    try {
        logger.debug("Attempting authentication for: {}", username);
        lc.login();
    } finally {
        lc.logout();
    }

    Principal principal = null;
    final Set<java.security.Principal> principals = lc.getSubject().getPrincipals();
    if (principals != null && principals.size() > 0) {
        principal = this.principalFactory.createPrincipal(principals.iterator().next().getName());
    }
    return createHandlerResult(credential, principal, null);
}
 
Example 10
Source File: KerberosAuthenticationHandler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Releases any resources initialized by the authentication handler.
 * <p>
 * It destroys the Kerberos context.
 */
@Override
public void destroy() {
  keytab = null;
  serverSubject = null;
  for (LoginContext loginContext : loginContexts) {
    try {
      loginContext.logout();
    } catch (LoginException ex) {
      LOG.warn(ex.getMessage(), ex);
    }
  }
  loginContexts.clear();
}
 
Example 11
Source File: KerberosUtilities.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
public byte[] buildToken(String clientPrincipalName, File clientKeyTabFile, String targetServerPrincipalName)
        throws Exception
{
    final LoginContext lc = createKerberosKeyTabLoginContext(INITIATE_SCOPE,
                                                             clientPrincipalName,
                                                             clientKeyTabFile);

    Subject clientSubject = null;
    String useSubjectCredsOnly = System.getProperty(USE_SUBJECT_CREDS_ONLY);
    try
    {
        debug("Before login");
        lc.login();
        clientSubject = lc.getSubject();
        debug("LoginContext subject {}", clientSubject);
        System.setProperty(USE_SUBJECT_CREDS_ONLY, "true");
        return Subject.doAs(clientSubject,
                            (PrivilegedExceptionAction<byte[]>) () -> buildTokenWithinSubjectWithKerberosTicket(
                                    clientPrincipalName,
                                    targetServerPrincipalName));
    }
    finally
    {
        if (useSubjectCredsOnly == null)
        {
            System.clearProperty(USE_SUBJECT_CREDS_ONLY);
        }
        else
        {
            System.setProperty(USE_SUBJECT_CREDS_ONLY, useSubjectCredsOnly);
        }
        if (clientSubject != null)
        {
            lc.logout();
        }
    }
}
 
Example 12
Source File: TestSecureLogins.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test
public void testZKServerContextLogin() throws Throwable {
  LoginContext client = login(ZOOKEEPER_LOCALHOST,
                              ZOOKEEPER_SERVER_CONTEXT,
                              keytab_zk);
  logLoginDetails(ZOOKEEPER_LOCALHOST, client);

  client.logout();
}
 
Example 13
Source File: LCTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    if (args.length < 2) {
        throw new RuntimeException("Incorrect test params");
    }
    String nameOfContext = args[0];
    boolean isPositive = Boolean.parseBoolean(args[1]);
    String actionName = null;
    if (args.length == 3) {
        actionName = args[2];
    }
    try {
        LoginContext lc = new LoginContext(nameOfContext,
                new MyCallbackHandler());
        lc.login();
        checkPrincipal(lc, true);
        lc.logout();
        checkPrincipal(lc, false);
        if (!isPositive) {
            throw new RuntimeException("Test failed. Exception expected.");
        }
    } catch (LoginException le) {
        if (isPositive) {
            throw new RuntimeException("Test failed. Unexpected " +
                    "exception", le);
        }
        System.out.println("Expected exception: "
                + le.getMessage());
    }
    checkActions(actionName);
    System.out.println("Test passed.");
}
 
Example 14
Source File: StandardCallbacks.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws LoginException {
    System.setProperty("java.security.auth.login.config",
            System.getProperty("test.src")
                    + System.getProperty("file.separator")
                    + "custom.config");

    CustomCallbackHandler handler = new CustomCallbackHandler(USERNAME);
    LoginContext context = new LoginContext("StandardCallbacks", handler);

    handler.setPassword(PASSWORD);
    System.out.println("Try to login with correct password, "
            + "successful authentication is expected");
    context.login();
    System.out.println("Authentication succeeded!");

    Subject subject = context.getSubject();
    System.out.println("Authenticated user has the following principals ["
            + subject.getPrincipals().size() + " ]:");
    boolean found = true;
    for (Principal principal : subject.getPrincipals()) {
        System.out.println("principal: " + principal);
        if (principal instanceof CustomLoginModule.TestPrincipal) {
            CustomLoginModule.TestPrincipal testPrincipal =
                    (CustomLoginModule.TestPrincipal) principal;
            if (USERNAME.equals(testPrincipal.getName())) {
                System.out.println("Found test principal: "
                        + testPrincipal);
                found = true;
                break;
            }
        }
    }

    if (!found) {
        throw new RuntimeException("TestPrincipal not found");
    }

    // check if all expected text output callbacks have been called
    if (!handler.info) {
        throw new RuntimeException("TextOutputCallback.INFO not called");
    }

    if (!handler.warning) {
        throw new RuntimeException("TextOutputCallback.WARNING not called");
    }

    if (!handler.error) {
        throw new RuntimeException("TextOutputCallback.ERROR not called");
    }

    System.out.println("Authenticated user has the following public "
            + "credentials [" + subject.getPublicCredentials().size()
            + "]:");
    subject.getPublicCredentials().stream().
            forEach((o) -> {
                System.out.println("public credential: " + o);
    });

    context.logout();

    System.out.println("Test passed");
}
 
Example 15
Source File: TestSecureLogins.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Test
public void testServerLogin() throws Throwable {
  LoginContext loginContext = createLoginContextZookeeperLocalhost();
  loginContext.login();
  loginContext.logout();
}
 
Example 16
Source File: StandardCallbacks.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws LoginException {
    System.setProperty("java.security.auth.login.config",
            System.getProperty("test.src")
                    + System.getProperty("file.separator")
                    + "custom.config");

    CustomCallbackHandler handler = new CustomCallbackHandler(USERNAME);
    LoginContext context = new LoginContext("StandardCallbacks", handler);

    handler.setPassword(PASSWORD);
    System.out.println("Try to login with correct password, "
            + "successful authentication is expected");
    context.login();
    System.out.println("Authentication succeeded!");

    Subject subject = context.getSubject();
    System.out.println("Authenticated user has the following principals ["
            + subject.getPrincipals().size() + " ]:");
    boolean found = true;
    for (Principal principal : subject.getPrincipals()) {
        System.out.println("principal: " + principal);
        if (principal instanceof CustomLoginModule.TestPrincipal) {
            CustomLoginModule.TestPrincipal testPrincipal =
                    (CustomLoginModule.TestPrincipal) principal;
            if (USERNAME.equals(testPrincipal.getName())) {
                System.out.println("Found test principal: "
                        + testPrincipal);
                found = true;
                break;
            }
        }
    }

    if (!found) {
        throw new RuntimeException("TestPrincipal not found");
    }

    // check if all expected text output callbacks have been called
    if (!handler.info) {
        throw new RuntimeException("TextOutputCallback.INFO not called");
    }

    if (!handler.warning) {
        throw new RuntimeException("TextOutputCallback.WARNING not called");
    }

    if (!handler.error) {
        throw new RuntimeException("TextOutputCallback.ERROR not called");
    }

    System.out.println("Authenticated user has the following public "
            + "credentials [" + subject.getPublicCredentials().size()
            + "]:");
    subject.getPublicCredentials().stream().
            forEach((o) -> {
                System.out.println("public credential: " + o);
    });

    context.logout();

    System.out.println("Test passed");
}
 
Example 17
Source File: UserGroupInformation.java    From hadoop with Apache License 2.0 4 votes vote down vote up
/**
 * Re-Login a user in from the ticket cache.  This
 * method assumes that login had happened already.
 * The Subject field of this UserGroupInformation object is updated to have
 * the new credentials.
 * @throws IOException on a failure
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public synchronized void reloginFromTicketCache()
throws IOException {
  if (!isSecurityEnabled() || 
      user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS ||
      !isKrbTkt)
    return;
  LoginContext login = getLogin();
  if (login == null) {
    throw new IOException("login must be done first");
  }
  long now = Time.now();
  if (!hasSufficientTimeElapsed(now)) {
    return;
  }
  // register most recent relogin attempt
  user.setLastLogin(now);
  try {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Initiating logout for " + getUserName());
    }
    //clear up the kerberos state. But the tokens are not cleared! As per 
    //the Java kerberos login module code, only the kerberos credentials
    //are cleared
    login.logout();
    //login and also update the subject field of this instance to 
    //have the new credentials (pass it to the LoginContext constructor)
    login = 
      newLoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, 
          getSubject(), new HadoopConfiguration());
    if (LOG.isDebugEnabled()) {
      LOG.debug("Initiating re-login for " + getUserName());
    }
    login.login();
    setLogin(login);
  } catch (LoginException le) {
    throw new IOException("Login failure for " + getUserName(), le);
  } 
}
 
Example 18
Source File: StandardCallbacks.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws LoginException {
    System.setProperty("java.security.auth.login.config",
            System.getProperty("test.src")
                    + System.getProperty("file.separator")
                    + "custom.config");

    CustomCallbackHandler handler = new CustomCallbackHandler(USERNAME);
    LoginContext context = new LoginContext("StandardCallbacks", handler);

    handler.setPassword(PASSWORD);
    System.out.println("Try to login with correct password, "
            + "successful authentication is expected");
    context.login();
    System.out.println("Authentication succeeded!");

    Subject subject = context.getSubject();
    System.out.println("Authenticated user has the following principals ["
            + subject.getPrincipals().size() + " ]:");
    boolean found = true;
    for (Principal principal : subject.getPrincipals()) {
        System.out.println("principal: " + principal);
        if (principal instanceof CustomLoginModule.TestPrincipal) {
            CustomLoginModule.TestPrincipal testPrincipal =
                    (CustomLoginModule.TestPrincipal) principal;
            if (USERNAME.equals(testPrincipal.getName())) {
                System.out.println("Found test principal: "
                        + testPrincipal);
                found = true;
                break;
            }
        }
    }

    if (!found) {
        throw new RuntimeException("TestPrincipal not found");
    }

    // check if all expected text output callbacks have been called
    if (!handler.info) {
        throw new RuntimeException("TextOutputCallback.INFO not called");
    }

    if (!handler.warning) {
        throw new RuntimeException("TextOutputCallback.WARNING not called");
    }

    if (!handler.error) {
        throw new RuntimeException("TextOutputCallback.ERROR not called");
    }

    System.out.println("Authenticated user has the following public "
            + "credentials [" + subject.getPublicCredentials().size()
            + "]:");
    subject.getPublicCredentials().stream().
            forEach((o) -> {
                System.out.println("public credential: " + o);
    });

    context.logout();

    System.out.println("Test passed");
}
 
Example 19
Source File: ClientLoginExampleBean.java    From datawave with Apache License 2.0 4 votes vote down vote up
@Schedule(hour = "*", minute = "*", second = "0", persistent = false)
public void doScheduledEvent() {
    try {
        // Grab the server certificate from the keystore (we are assuming it is the first one).
        // This is the credential we'll set on the object callback.
        KeyStore keystore = domain.getKeyStore();
        final X509Certificate cert = (X509Certificate) keystore.getCertificate(keystore.aliases().nextElement());
        
        // Compute the username. This would either be just a user DN if you are using a user's client
        // certificate, or a server DN combined with a proxied user DN as we demonstrate here.
        String userDN = System.getenv("USER_DN"); // Normally a username would go here. Hack for local testing--query the sid running jboss.
        String userIssuerDN = System.getenv("ISSUER_DN"); // We need the issuer of the user's cert. This needs to be set in the environment for this test.
        String serverDN = cert.getSubjectX500Principal().getName();
        String serverIssuerDN = cert.getIssuerX500Principal().getName();
        final String dn = DnUtils.buildNormalizedProxyDN(serverDN, serverIssuerDN, userDN, userIssuerDN);
        
        // Handle the callback for authentication. We expect two callbacks, a NameCallback and an ObjectCallback.
        CallbackHandler cbh = new CallbackHandler() {
            @Override
            public void handle(Callback[] callbacks) {
                NameCallback nc = (NameCallback) callbacks[0];
                ObjectCallback oc = (ObjectCallback) callbacks[1];
                nc.setName(dn);
                oc.setCredential(cert);
            }
        };
        
        // Authenticate to the DATAWAVE client domain. This saves the credentials
        // we passed in the callback handler above, and passes them along to the server
        // when we attempt any calls that require a login on the server.
        LoginContext lc = new LoginContext("datawave-client", cbh);
        lc.login();
        
        // Call secured EJBs
        try {
            AuthorizationsListBase auths = userOps.listEffectiveAuthorizations();
            System.err.println("***** Auths for user " + dn + " are: " + auths);
        } finally {
            // Logout, which will restore previous credentials, if any.
            // Be sure to do this in a finally block.
            lc.logout();
        }
    } catch (Exception e) {
        System.err.println("Error doing login!");
        e.printStackTrace(System.err);
    }
}
 
Example 20
Source File: StandardCallbacks.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws LoginException {
    System.setProperty("java.security.auth.login.config",
            System.getProperty("test.src")
                    + System.getProperty("file.separator")
                    + "custom.config");

    CustomCallbackHandler handler = new CustomCallbackHandler(USERNAME);
    LoginContext context = new LoginContext("StandardCallbacks", handler);

    handler.setPassword(PASSWORD);
    System.out.println("Try to login with correct password, "
            + "successful authentication is expected");
    context.login();
    System.out.println("Authentication succeeded!");

    Subject subject = context.getSubject();
    System.out.println("Authenticated user has the following principals ["
            + subject.getPrincipals().size() + " ]:");
    boolean found = true;
    for (Principal principal : subject.getPrincipals()) {
        System.out.println("principal: " + principal);
        if (principal instanceof CustomLoginModule.TestPrincipal) {
            CustomLoginModule.TestPrincipal testPrincipal =
                    (CustomLoginModule.TestPrincipal) principal;
            if (USERNAME.equals(testPrincipal.getName())) {
                System.out.println("Found test principal: "
                        + testPrincipal);
                found = true;
                break;
            }
        }
    }

    if (!found) {
        throw new RuntimeException("TestPrincipal not found");
    }

    // check if all expected text output callbacks have been called
    if (!handler.info) {
        throw new RuntimeException("TextOutputCallback.INFO not called");
    }

    if (!handler.warning) {
        throw new RuntimeException("TextOutputCallback.WARNING not called");
    }

    if (!handler.error) {
        throw new RuntimeException("TextOutputCallback.ERROR not called");
    }

    System.out.println("Authenticated user has the following public "
            + "credentials [" + subject.getPublicCredentials().size()
            + "]:");
    subject.getPublicCredentials().stream().
            forEach((o) -> {
                System.out.println("public credential: " + o);
    });

    context.logout();

    System.out.println("Test passed");
}