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

The following examples show how to use javax.security.auth.login.LoginContext#getSubject() . 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: JaasKrbUtil.java    From deprecated-security-advanced-modules with Apache License 2.0 8 votes vote down vote up
public static Subject loginUsingKeytab(final Set<String> principalAsStrings, final Path keytabPath, final boolean initiator) throws LoginException {
    final Set<Principal> principals = new HashSet<Principal>();

    for(String p: principalAsStrings) {
        principals.add(new KerberosPrincipal(p));
    }


    final Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());

    final Configuration conf = useKeytab("*", keytabPath, initiator);
    final String confName = "KeytabConf";
    final LoginContext loginContext = new LoginContext(confName, subject, null, conf);
    loginContext.login();
    return loginContext.getSubject();
}
 
Example 2
Source File: KerberosConnection.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
/**
 * Performs a kerberos login, possibly logging out first.
 *
 * @param prevContext The LoginContext from the previous login, or null
 * @param conf JAAS Configuration object
 * @param subject The JAAS Subject
 * @return The context and subject from the login
 * @throws LoginException If the login failed.
 */
Entry<LoginContext, Subject> login(LoginContext prevContext, Configuration conf,
    Subject subject) throws LoginException {
  // Is synchronized by the caller

  // If a context was provided, perform a logout first
  if (null != prevContext) {
    prevContext.logout();
  }

  // Create a LoginContext given the Configuration and Subject
  LoginContext loginContext = createLoginContext(conf);
  // Invoke the login
  loginContext.login();
  // Get the Subject from the context and verify it's non-null (null would imply failure)
  Subject loggedInSubject = loginContext.getSubject();
  if (null == loggedInSubject) {
    throw new RuntimeException("Failed to perform Kerberos login");
  }

  // Send it back to the caller to use with launchRenewalThread
  return new AbstractMap.SimpleEntry<>(loginContext, loggedInSubject);
}
 
Example 3
Source File: GSSUtil.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Authenticate using the login module from the specified
 * configuration entry.
 *
 * @param caller the caller of JAAS Login
 * @param mech the mech to be used
 * @return the authenticated subject
 */
public static Subject login(GSSCaller caller, Oid mech) throws LoginException {

    CallbackHandler cb = null;
    if (caller instanceof HttpCaller) {
        cb = new sun.net.www.protocol.http.spnego.NegotiateCallbackHandler(
                ((HttpCaller)caller).info());
    } else {
        String defaultHandler =
                java.security.Security.getProperty(DEFAULT_HANDLER);
        // get the default callback handler
        if ((defaultHandler != null) && (defaultHandler.length() != 0)) {
            cb = null;
        } else {
            cb = new ConsoleCallbackHandler();
        }
    }

    // New instance of LoginConfigImpl must be created for each login,
    // since the entry name is not passed as the first argument, but
    // generated with caller and mech inside LoginConfigImpl
    LoginContext lc = new LoginContext("", null, cb,
            new LoginConfigImpl(caller, mech));
    lc.login();
    return lc.getSubject();
}
 
Example 4
Source File: KrbTicket.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    // define principals
    Map<String, String> principals = new HashMap<>();
    principals.put(USER_PRINCIPAL, PASSWORD);
    principals.put(KRBTGT_PRINCIPAL, null);

    System.setProperty("java.security.krb5.conf", KRB5_CONF_FILENAME);

    // start a local KDC instance
    KDC kdc = KDC.startKDC(HOST, null, REALM, principals, null, null);
    KDC.saveConfig(KRB5_CONF_FILENAME, kdc,
            "forwardable = true", "proxiable = true");

    // create JAAS config
    Files.write(Paths.get(JAAS_CONF), Arrays.asList(
            "Client {",
            "    com.sun.security.auth.module.Krb5LoginModule required;",
            "};"
    ));
    System.setProperty("java.security.auth.login.config", JAAS_CONF);
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    long startTime = Instant.now().getEpochSecond() * 1000;

    LoginContext lc = new LoginContext("Client",
            new Helper.UserPasswordHandler(USER, PASSWORD));
    lc.login();

    Subject subject = lc.getSubject();
    System.out.println("subject: " + subject);

    Set creds = subject.getPrivateCredentials(
            KerberosTicket.class);

    if (creds.size() > 1) {
        throw new RuntimeException("Multiple credintials found");
    }

    Object o = creds.iterator().next();
    if (!(o instanceof KerberosTicket)) {
        throw new RuntimeException("Instance of KerberosTicket expected");
    }
    KerberosTicket krbTkt = (KerberosTicket) o;

    System.out.println("forwardable = " + krbTkt.isForwardable());
    System.out.println("proxiable   = " + krbTkt.isProxiable());
    System.out.println("renewable   = " + krbTkt.isRenewable());
    System.out.println("current     = " + krbTkt.isCurrent());

    if (!krbTkt.isForwardable()) {
        throw new RuntimeException("Forwardable ticket expected");
    }

    if (!krbTkt.isProxiable()) {
        throw new RuntimeException("Proxiable ticket expected");
    }

    if (!krbTkt.isCurrent()) {
        throw new RuntimeException("Ticket is not current");
    }

    if (krbTkt.isRenewable()) {
        throw new RuntimeException("Not renewable ticket expected");
    }
    try {
        krbTkt.refresh();
        throw new RuntimeException(
                "Expected RefreshFailedException not thrown");
    } catch(RefreshFailedException e) {
        System.out.println("Expected exception: " + e);
    }

    if (!checkTime(krbTkt, startTime)) {
        throw new RuntimeException("Wrong ticket life time");
    }

    krbTkt.destroy();
    if (!krbTkt.isDestroyed()) {
        throw new RuntimeException("Ticket not destroyed");
    }

    System.out.println("Test passed");
}
 
Example 5
Source File: SSLAndKerberosTest.java    From atlas with Apache License 2.0 6 votes vote down vote up
protected Subject loginTestUser() throws LoginException, IOException {
    LoginContext lc = new LoginContext(TEST_USER_JAAS_SECTION, new CallbackHandler() {

        @Override
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback callback : callbacks) {
                if (callback instanceof PasswordCallback) {
                    PasswordCallback passwordCallback = (PasswordCallback) callback;
                    passwordCallback.setPassword(TESTPASS.toCharArray());
                }
                if (callback instanceof NameCallback) {
                    NameCallback nameCallback = (NameCallback) callback;
                    nameCallback.setName(TESTUSER);
                }
            }
        }
    });
    // attempt authentication
    lc.login();
    return lc.getSubject();
}
 
Example 6
Source File: JaasKrbUtil.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
public static Subject loginUsingTicketCache(final String principal, final Path cachePath) throws LoginException {
    final Set<Principal> principals = new HashSet<Principal>();
    principals.add(new KerberosPrincipal(principal));

    final Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());

    final Configuration conf = useTicketCache(principal, cachePath);
    final String confName = "TicketCacheConf";
    final LoginContext loginContext = new LoginContext(confName, subject, null, conf);
    loginContext.login();
    return loginContext.getSubject();
}
 
Example 7
Source File: KerberosAuthentication.java    From presto with Apache License 2.0 5 votes vote down vote up
public Subject getSubject()
{
    Subject subject = new Subject(false, ImmutableSet.of(principal), emptySet(), emptySet());
    try {
        LoginContext loginContext = new LoginContext("", subject, null, configuration);
        loginContext.login();
        return loginContext.getSubject();
    }
    catch (LoginException e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: JaasKrbUtil.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
public static Subject loginUsingPassword(final String principal, final String password) throws LoginException {
    final Set<Principal> principals = new HashSet<Principal>();
    principals.add(new KerberosPrincipal(principal));

    final Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());

    final Configuration conf = usePassword(principal);
    final String confName = "PasswordConf";
    final CallbackHandler callback = new KrbCallbackHandler(principal, password);
    final LoginContext loginContext = new LoginContext(confName, subject, callback, conf);
    loginContext.login();
    return loginContext.getSubject();
}
 
Example 9
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 10
Source File: RegistryTestHelper.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Log the details of a login context
 * @param name name to assert that the user is logged in as
 * @param loginContext the login context
 */
public static void logLoginDetails(String name,
    LoginContext loginContext) {
  assertNotNull("Null login context", loginContext);
  Subject subject = loginContext.getSubject();
  LOG.info("Logged in as {}:\n {}", name, subject);
}
 
Example 11
Source File: Context.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Logins with a JAAS login config entry name
 */
public static Context fromJAAS(final String name) throws Exception {
    Context out = new Context();
    out.name = name;
    LoginContext lc = new LoginContext(name);
    lc.login();
    out.s = lc.getSubject();
    return out;
}
 
Example 12
Source File: KrbTicket.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    // define principals
    Map<String, String> principals = new HashMap<>();
    principals.put(USER_PRINCIPAL, PASSWORD);
    principals.put(KRBTGT_PRINCIPAL, null);

    System.setProperty("java.security.krb5.conf", KRB5_CONF_FILENAME);

    // start a local KDC instance
    KDC kdc = KDC.startKDC(HOST, null, REALM, principals, null, null);
    KDC.saveConfig(KRB5_CONF_FILENAME, kdc,
            "forwardable = true", "proxiable = true");

    // create JAAS config
    Files.write(Paths.get(JAAS_CONF), Arrays.asList(
            "Client {",
            "    com.sun.security.auth.module.Krb5LoginModule required;",
            "};"
    ));
    System.setProperty("java.security.auth.login.config", JAAS_CONF);
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    long startTime = Instant.now().getEpochSecond() * 1000;

    LoginContext lc = new LoginContext("Client",
            new Helper.UserPasswordHandler(USER, PASSWORD));
    lc.login();

    Subject subject = lc.getSubject();
    System.out.println("subject: " + subject);

    Set creds = subject.getPrivateCredentials(
            KerberosTicket.class);

    if (creds.size() > 1) {
        throw new RuntimeException("Multiple credintials found");
    }

    Object o = creds.iterator().next();
    if (!(o instanceof KerberosTicket)) {
        throw new RuntimeException("Instance of KerberosTicket expected");
    }
    KerberosTicket krbTkt = (KerberosTicket) o;

    System.out.println("forwardable = " + krbTkt.isForwardable());
    System.out.println("proxiable   = " + krbTkt.isProxiable());
    System.out.println("renewable   = " + krbTkt.isRenewable());
    System.out.println("current     = " + krbTkt.isCurrent());

    if (!krbTkt.isForwardable()) {
        throw new RuntimeException("Forwardable ticket expected");
    }

    if (!krbTkt.isProxiable()) {
        throw new RuntimeException("Proxiable ticket expected");
    }

    if (!krbTkt.isCurrent()) {
        throw new RuntimeException("Ticket is not current");
    }

    if (krbTkt.isRenewable()) {
        throw new RuntimeException("Not renewable ticket expected");
    }
    try {
        krbTkt.refresh();
        throw new RuntimeException(
                "Expected RefreshFailedException not thrown");
    } catch(RefreshFailedException e) {
        System.out.println("Expected exception: " + e);
    }

    if (!checkTime(krbTkt, startTime)) {
        throw new RuntimeException("Wrong ticket life time");
    }

    krbTkt.destroy();
    if (!krbTkt.isDestroyed()) {
        throw new RuntimeException("Ticket not destroyed");
    }

    System.out.println("Test passed");
}
 
Example 13
Source File: UserGroupInformation.java    From hadoop with Apache License 2.0 4 votes vote down vote up
/**
 * Create a UserGroupInformation from a Kerberos ticket cache.
 * 
 * @param user                The principal name to load from the ticket
 *                            cache
 * @param ticketCachePath     the path to the ticket cache file
 *
 * @throws IOException        if the kerberos login fails
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
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);
  }
}
 
Example 14
Source File: StandardCallbacks.java    From openjdk-jdk8u-backup 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: 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 16
Source File: KrbTicket.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    // define principals
    Map<String, String> principals = new HashMap<>();
    principals.put(USER_PRINCIPAL, PASSWORD);
    principals.put(KRBTGT_PRINCIPAL, null);

    System.setProperty("java.security.krb5.conf", KRB5_CONF_FILENAME);

    // start a local KDC instance
    KDC kdc = KDC.startKDC(HOST, null, REALM, principals, null, null);
    KDC.saveConfig(KRB5_CONF_FILENAME, kdc,
            "forwardable = true", "proxiable = true");

    // create JAAS config
    Files.write(Paths.get(JAAS_CONF), Arrays.asList(
            "Client {",
            "    com.sun.security.auth.module.Krb5LoginModule required;",
            "};"
    ));
    System.setProperty("java.security.auth.login.config", JAAS_CONF);
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    long startTime = Instant.now().getEpochSecond() * 1000;

    LoginContext lc = new LoginContext("Client",
            new Helper.UserPasswordHandler(USER, PASSWORD));
    lc.login();

    Subject subject = lc.getSubject();
    System.out.println("subject: " + subject);

    Set creds = subject.getPrivateCredentials(
            KerberosTicket.class);

    if (creds.size() > 1) {
        throw new RuntimeException("Multiple credintials found");
    }

    Object o = creds.iterator().next();
    if (!(o instanceof KerberosTicket)) {
        throw new RuntimeException("Instance of KerberosTicket expected");
    }
    KerberosTicket krbTkt = (KerberosTicket) o;

    System.out.println("forwardable = " + krbTkt.isForwardable());
    System.out.println("proxiable   = " + krbTkt.isProxiable());
    System.out.println("renewable   = " + krbTkt.isRenewable());
    System.out.println("current     = " + krbTkt.isCurrent());

    if (!krbTkt.isForwardable()) {
        throw new RuntimeException("Forwardable ticket expected");
    }

    if (!krbTkt.isProxiable()) {
        throw new RuntimeException("Proxiable ticket expected");
    }

    if (!krbTkt.isCurrent()) {
        throw new RuntimeException("Ticket is not current");
    }

    if (krbTkt.isRenewable()) {
        throw new RuntimeException("Not renewable ticket expected");
    }
    try {
        krbTkt.refresh();
        throw new RuntimeException(
                "Expected RefreshFailedException not thrown");
    } catch(RefreshFailedException e) {
        System.out.println("Expected exception: " + e);
    }

    if (!checkTime(krbTkt, startTime)) {
        throw new RuntimeException("Wrong ticket life time");
    }

    krbTkt.destroy();
    if (!krbTkt.isDestroyed()) {
        throw new RuntimeException("Ticket not destroyed");
    }

    System.out.println("Test passed");
}
 
Example 17
Source File: StandardCallbacks.java    From TencentKona-8 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 18
Source File: SimpleLDAPAuthenticationManagerImpl.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private Subject doGssApiLogin(final String configScope) throws LoginException
{
    LoginContext loginContext = new LoginContext(configScope);
    loginContext.login();
    return loginContext.getSubject();
}
 
Example 19
Source File: KrbTicket.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    // define principals
    Map<String, String> principals = new HashMap<>();
    principals.put(USER_PRINCIPAL, PASSWORD);
    principals.put(KRBTGT_PRINCIPAL, null);

    System.setProperty("java.security.krb5.conf", KRB5_CONF_FILENAME);

    // start a local KDC instance
    KDC kdc = KDC.startKDC(HOST, null, REALM, principals, null, null);
    KDC.saveConfig(KRB5_CONF_FILENAME, kdc,
            "forwardable = true", "proxiable = true");

    // create JAAS config
    Files.write(Paths.get(JAAS_CONF), Arrays.asList(
            "Client {",
            "    com.sun.security.auth.module.Krb5LoginModule required;",
            "};"
    ));
    System.setProperty("java.security.auth.login.config", JAAS_CONF);
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    long startTime = Instant.now().getEpochSecond() * 1000;

    LoginContext lc = new LoginContext("Client",
            new Helper.UserPasswordHandler(USER, PASSWORD));
    lc.login();

    Subject subject = lc.getSubject();
    System.out.println("subject: " + subject);

    Set creds = subject.getPrivateCredentials(
            KerberosTicket.class);

    if (creds.size() > 1) {
        throw new RuntimeException("Multiple credintials found");
    }

    Object o = creds.iterator().next();
    if (!(o instanceof KerberosTicket)) {
        throw new RuntimeException("Instance of KerberosTicket expected");
    }
    KerberosTicket krbTkt = (KerberosTicket) o;

    System.out.println("forwardable = " + krbTkt.isForwardable());
    System.out.println("proxiable   = " + krbTkt.isProxiable());
    System.out.println("renewable   = " + krbTkt.isRenewable());
    System.out.println("current     = " + krbTkt.isCurrent());

    if (!krbTkt.isForwardable()) {
        throw new RuntimeException("Forwardable ticket expected");
    }

    if (!krbTkt.isProxiable()) {
        throw new RuntimeException("Proxiable ticket expected");
    }

    if (!krbTkt.isCurrent()) {
        throw new RuntimeException("Ticket is not current");
    }

    if (krbTkt.isRenewable()) {
        throw new RuntimeException("Not renewable ticket expected");
    }
    try {
        krbTkt.refresh();
        throw new RuntimeException(
                "Expected RefreshFailedException not thrown");
    } catch(RefreshFailedException e) {
        System.out.println("Expected exception: " + e);
    }

    if (!checkTime(krbTkt, startTime)) {
        throw new RuntimeException("Wrong ticket life time");
    }

    krbTkt.destroy();
    if (!krbTkt.isDestroyed()) {
        throw new RuntimeException("Ticket not destroyed");
    }

    System.out.println("Test passed");
}
 
Example 20
Source File: KrbTicket.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    // define principals
    Map<String, String> principals = new HashMap<>();
    principals.put(USER_PRINCIPAL, PASSWORD);
    principals.put(KRBTGT_PRINCIPAL, null);

    System.setProperty("java.security.krb5.conf", KRB5_CONF_FILENAME);

    // start a local KDC instance
    KDC kdc = KDC.startKDC(HOST, null, REALM, principals, null, null);
    KDC.saveConfig(KRB5_CONF_FILENAME, kdc,
            "forwardable = true", "proxiable = true");

    // create JAAS config
    Files.write(Paths.get(JAAS_CONF), Arrays.asList(
            "Client {",
            "    com.sun.security.auth.module.Krb5LoginModule required;",
            "};"
    ));
    System.setProperty("java.security.auth.login.config", JAAS_CONF);
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    long startTime = Instant.now().getEpochSecond() * 1000;

    LoginContext lc = new LoginContext("Client",
            new Helper.UserPasswordHandler(USER, PASSWORD));
    lc.login();

    Subject subject = lc.getSubject();
    System.out.println("subject: " + subject);

    Set creds = subject.getPrivateCredentials(
            KerberosTicket.class);

    if (creds.size() > 1) {
        throw new RuntimeException("Multiple credintials found");
    }

    Object o = creds.iterator().next();
    if (!(o instanceof KerberosTicket)) {
        throw new RuntimeException("Instance of KerberosTicket expected");
    }
    KerberosTicket krbTkt = (KerberosTicket) o;

    System.out.println("forwardable = " + krbTkt.isForwardable());
    System.out.println("proxiable   = " + krbTkt.isProxiable());
    System.out.println("renewable   = " + krbTkt.isRenewable());
    System.out.println("current     = " + krbTkt.isCurrent());

    if (!krbTkt.isForwardable()) {
        throw new RuntimeException("Forwardable ticket expected");
    }

    if (!krbTkt.isProxiable()) {
        throw new RuntimeException("Proxiable ticket expected");
    }

    if (!krbTkt.isCurrent()) {
        throw new RuntimeException("Ticket is not current");
    }

    if (krbTkt.isRenewable()) {
        throw new RuntimeException("Not renewable ticket expected");
    }
    try {
        krbTkt.refresh();
        throw new RuntimeException(
                "Expected RefreshFailedException not thrown");
    } catch(RefreshFailedException e) {
        System.out.println("Expected exception: " + e);
    }

    if (!checkTime(krbTkt, startTime)) {
        throw new RuntimeException("Wrong ticket life time");
    }

    krbTkt.destroy();
    if (!krbTkt.isDestroyed()) {
        throw new RuntimeException("Ticket not destroyed");
    }

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