Java Code Examples for javax.security.auth.login.LoginContext

The following examples show how to use javax.security.auth.login.LoginContext. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: openjdk-jdk9   Source File: GSSUtil.java    License: 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 2
Source Project: hadoop   Source File: TestSecureLogins.java    License: 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 3
public static void testLogin(String confName, char[] passwd,
        Configuration cf, boolean expectException) {
    try {
        CallbackHandler ch = new MyCallbackHandler("testUser", passwd);
        LoginContext lc = new LoginContext(confName, new Subject(),
                ch, cf);
        lc.login();
        if (expectException) {
            throw new RuntimeException("Login Test failed: "
                    + "expected LoginException not thrown");
        }
    } catch (LoginException le) {
        if (!expectException) {
            System.out.println("Login Test failed: "
                    + "received Unexpected exception.");
            throw new RuntimeException(le);
        }
    }
}
 
Example 4
Source Project: calcite-avatica   Source File: KerberosConnectionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void noPreviousContextOnLogin() throws Exception {
  KerberosConnection krbUtil = mock(KerberosConnection.class);
  Subject subject = new Subject();
  Subject loggedInSubject = new Subject();
  Configuration conf = mock(Configuration.class);
  LoginContext context = mock(LoginContext.class);

  // Call the real login(LoginContext, Configuration, Subject) method
  when(krbUtil.login(nullable(LoginContext.class), any(Configuration.class), any(Subject.class)))
      .thenCallRealMethod();
  // Return a fake LoginContext
  when(krbUtil.createLoginContext(conf)).thenReturn(context);
  // Return a fake Subject from that fake LoginContext
  when(context.getSubject()).thenReturn(loggedInSubject);

  Entry<LoginContext, Subject> pair = krbUtil.login(null, conf, subject);

  // Verify we get the fake LoginContext and Subject
  assertEquals(context, pair.getKey());
  assertEquals(loggedInSubject, pair.getValue());

  // login should be called on the LoginContext
  verify(context).login();
}
 
Example 5
public static void testConfigName(String confName,
        boolean expectException) {
    String expectedMsg = "No LoginModules configured for " + confName;
    try {
        LoginContext lc = new LoginContext(confName, new Subject(),
                new MyCallbackHandler(), new MyConfiguration());

        if (expectException) {
            throw new RuntimeException("Wrong Config Name Test failed: "
                    + "expected LoginException not thrown.");
        }
    } catch (LoginException le) {
        if (!expectException || !le.getMessage().equals(expectedMsg)) {
            System.out.println("Wrong Config Name Test failed: "
                    + "received Unexpected exception.");
            throw new RuntimeException(le);
        }
    }
}
 
Example 6
public static void testConfigName(String confName,
        boolean expectException) {
    String expectedMsg = "No LoginModules configured for " + confName;
    try {
        LoginContext lc = new LoginContext(confName, new Subject(),
                new MyCallbackHandler(), new MyConfiguration());

        if (expectException) {
            throw new RuntimeException("Wrong Config Name Test failed: "
                    + "expected LoginException not thrown.");
        }
    } catch (LoginException le) {
        if (!expectException || !le.getMessage().equals(expectedMsg)) {
            System.out.println("Wrong Config Name Test failed: "
                    + "received Unexpected exception.");
            throw new RuntimeException(le);
        }
    }
}
 
Example 7
Source Project: TencentKona-8   Source File: LCTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void checkPrincipal(LoginContext loginContext, boolean
        principalShouldExist) {
    if (!principalShouldExist) {
        if (loginContext.getSubject().getPrincipals().size() != 0) {
            throw new RuntimeException("Test failed. Principal was not " +
                    "cleared.");
        }
    } else {
        for (Principal p : loginContext.getSubject().getPrincipals()) {
            if (p instanceof UnixPrincipal &&
                    USER_NAME.equals(p.getName())) {
                //Proper principal was found, return.
                return;
            }
        }
        throw new RuntimeException("Test failed. UnixPrincipal "
                + USER_NAME + " expected.");
    }
}
 
Example 8
public static void testLogin(String confName, char[] passwd,
        Configuration cf, boolean expectException) {
    try {
        CallbackHandler ch = new MyCallbackHandler("testUser", passwd);
        LoginContext lc = new LoginContext(confName, new Subject(),
                ch, cf);
        lc.login();
        if (expectException) {
            throw new RuntimeException("Login Test failed: "
                    + "expected LoginException not thrown");
        }
    } catch (LoginException le) {
        if (!expectException) {
            System.out.println("Login Test failed: "
                    + "received Unexpected exception.");
            throw new RuntimeException(le);
        }
    }
}
 
Example 9
public static void testConfigName(String confName,
        boolean expectException) {
    String expectedMsg = "No LoginModules configured for " + confName;
    try {
        LoginContext lc = new LoginContext(confName, new Subject(),
                new MyCallbackHandler(), new MyConfiguration());

        if (expectException) {
            throw new RuntimeException("Wrong Config Name Test failed: "
                    + "expected LoginException not thrown.");
        }
    } catch (LoginException le) {
        if (!expectException || !le.getMessage().equals(expectedMsg)) {
            System.out.println("Wrong Config Name Test failed: "
                    + "received Unexpected exception.");
            throw new RuntimeException(le);
        }
    }
}
 
Example 10
Source Project: pxf   Source File: PxfUserGroupInformationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {

    // prepare objects
    nowMs = System.currentTimeMillis();
    configuration = new Configuration();
    user = new User("user");
    serverName = "server";

    // prepare common mocks
    mockTGT = PowerMockito.mock(KerberosTicket.class); // has final methods, needs PowerMock to mock it

    // subject will have a known User as principal and mock TGT credential, train it to have appropriate expiration
    subject = new Subject(false, Sets.newHashSet(user), Sets.newHashSet(), Sets.newHashSet(mockTGT));

    // train to return mock Login Context when created with constructor
    mockLoginContext = mock(LoginContext.class);
    PowerMockito.whenNew(LoginContext.class).withAnyArguments().thenReturn(mockLoginContext);

    // setup PUGI to use a known subject instead of creating a brand new one
    Supplier<Subject> subjectProvider = () -> subject;
    Whitebox.setInternalState(PxfUserGroupInformation.class, subjectProvider);
    doNothing().when(mockLoginContext).login();
}
 
Example 11
Source Project: hadoop   Source File: TestSecureRegistry.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * have the ZK user create the root dir.
 * This logs out the ZK user after and stops its curator instance,
 * to avoid contamination
 * @throws Throwable
 */
public void userZookeeperToCreateRoot() throws Throwable {

  System.setProperty("curator-log-events", "true");
  CuratorService curator = null;
  LoginContext login = login(ZOOKEEPER_LOCALHOST,
      ZOOKEEPER_CLIENT_CONTEXT,
      keytab_zk);
  try {
    logLoginDetails(ZOOKEEPER, login);
    RegistrySecurity.setZKSaslClientProperties(ZOOKEEPER,
        ZOOKEEPER_CLIENT_CONTEXT);
    curator = startCuratorServiceInstance("ZK", true);
    LOG.info(curator.toString());

    addToTeardown(curator);
    curator.zkMkPath("/", CreateMode.PERSISTENT, false,
        RegistrySecurity.WorldReadWriteACL);
    ZKPathDumper pathDumper = curator.dumpPath(true);
    LOG.info(pathDumper.toString());
  } finally {
    logout(login);
    ServiceOperations.stop(curator);
  }
}
 
Example 12
Source Project: davmail   Source File: KerberosHelper.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create server side Kerberos login context for provided credentials.
 *
 * @param serverPrincipal server principal
 * @param serverPassword  server passsword
 * @return LoginContext server login context
 * @throws LoginException on error
 */
public static LoginContext serverLogin(final String serverPrincipal, final String serverPassword) throws LoginException {
    LoginContext serverLoginContext = new LoginContext("spnego-server", callbacks -> {
        for (Callback callback : callbacks) {
            if (callback instanceof NameCallback) {
                final NameCallback nameCallback = (NameCallback) callback;
                nameCallback.setName(serverPrincipal);
            } else if (callback instanceof PasswordCallback) {
                final PasswordCallback passCallback = (PasswordCallback) callback;
                passCallback.setPassword(serverPassword.toCharArray());
            } else {
                throw new UnsupportedCallbackException(callback);
            }
        }

    });
    serverLoginContext.login();
    return serverLoginContext;
}
 
Example 13
public static void testLogin(String confName, char[] passwd,
        Configuration cf, boolean expectException) {
    try {
        CallbackHandler ch = new MyCallbackHandler("testUser", passwd);
        LoginContext lc = new LoginContext(confName, new Subject(),
                ch, cf);
        lc.login();
        if (expectException) {
            throw new RuntimeException("Login Test failed: "
                    + "expected LoginException not thrown");
        }
    } catch (LoginException le) {
        if (!expectException) {
            System.out.println("Login Test failed: "
                    + "received Unexpected exception.");
            throw new RuntimeException(le);
        }
    }
}
 
Example 14
Source Project: openjdk-jdk9   Source File: AllPlatforms.java    License: GNU General Public License v2.0 6 votes vote down vote up
static void login(String test, String... conf) throws Exception {
    System.out.println("Testing " + test + "...");

    StringBuilder sb = new StringBuilder();
    sb.append("hello {\n");
    for (int i=0; i<conf.length; i+=2) {
        sb.append("    com.sun.security.auth.module." + conf[i]
                + " " + conf[i+1] + ";\n");
    }
    sb.append("};\n");
    Files.write(Paths.get(test), sb.toString().getBytes());

    // Must be called. Configuration has an internal static field.
    Configuration.setConfiguration(null);
    System.setProperty("java.security.auth.login.config", test);

    LoginContext lc = new LoginContext("hello");
    lc.login();
    System.out.println(lc.getSubject());
}
 
Example 15
public static void testConfigName(String confName,
        boolean expectException) {
    String expectedMsg = "No LoginModules configured for " + confName;
    try {
        LoginContext lc = new LoginContext(confName, new Subject(),
                new MyCallbackHandler(), new MyConfiguration());

        if (expectException) {
            throw new RuntimeException("Wrong Config Name Test failed: "
                    + "expected LoginException not thrown.");
        }
    } catch (LoginException le) {
        if (!expectException || !le.getMessage().equals(expectedMsg)) {
            System.out.println("Wrong Config Name Test failed: "
                    + "received Unexpected exception.");
            throw new RuntimeException(le);
        }
    }
}
 
Example 16
Source Project: openjdk-jdk9   Source File: Loader.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        System.setProperty("java.security.auth.login.config",
                new File(System.getProperty("test.src"), "sl.conf").toString());
        LoginContext lc = new LoginContext("me");

        if (SecondLoginModule.isLoaded) {
            throw new Exception();
        }

        lc.login();

        // Although only FirstLoginModule is specified in the JAAS login
        // config file, LoginContext will first create all LoginModule
        // implementations that are registered as services, which include
        // SecondLoginModule.
        if (!SecondLoginModule.isLoaded) {
            throw new Exception();
        }
    }
 
Example 17
Source Project: atlas   Source File: SSLAndKerberosTest.java    License: 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 18
Source Project: Tomcat7.0.67   Source File: GenericPrincipal.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Construct a new Principal, associated with the specified Realm, for the
 * specified username and password, with the specified role names
 * (as Strings).
 *
 * @param name The username of the user represented by this Principal
 * @param password Credentials used to authenticate this user
 * @param roles List of roles (must be Strings) possessed by this user
 * @param userPrincipal - the principal to be returned from the request 
 *        getUserPrincipal call if not null; if null, this will be returned
 * @param loginContext  - If provided, this will be used to log out the user
 *        at the appropriate time
 * @param gssCredential - If provided, the user&apos;s delegated credentials
 */
public GenericPrincipal(String name, String password, List<String> roles,
        Principal userPrincipal, LoginContext loginContext,
        GSSCredential gssCredential) {
    super();
    this.name = name;
    this.password = password;
    this.userPrincipal = userPrincipal;
    if (roles != null) {
        this.roles = new String[roles.size()];
        this.roles = roles.toArray(this.roles);
        if (this.roles.length > 1)
            Arrays.sort(this.roles);
    }
    this.loginContext = loginContext;
    this.gssCredential = gssCredential;
}
 
Example 19
Source Project: lams   Source File: SubjectActions.java    License: GNU General Public License v2.0 6 votes vote down vote up
static LoginContext createLoginContext(String securityDomain, Subject subject,
   CallbackHandler handler)
   throws LoginException
{
   LoginContextAction action = new LoginContextAction(securityDomain, subject, handler);
   try
   {
      LoginContext lc = (LoginContext) AccessController.doPrivileged(action);
      return lc;
   }
   catch(PrivilegedActionException e)
   {
      Exception ex = e.getException();
      if( ex instanceof LoginException )
         throw (LoginException) ex;
      else
         throw new LoginException(ex.getMessage());
   }
}
 
Example 20
public static void main(String[] args) throws Exception {
    try {
        LoginContext lc = new LoginContext(TEST_NAME);
        lc.login();
        throw new RuntimeException("Test Case Failed, did not get "
                + "expected exception");
    } catch (Exception ex) {
        if (ex.getMessage().contains("java.io.IOException: "
                + "Configuration Error:")) {
            System.out.println("Test case passed");
        } else {
            throw new RuntimeException(ex);
        }
    }
}
 
Example 21
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 22
Source Project: Bats   Source File: KerberosAuth.java    License: Apache License 2.0 5 votes vote down vote up
public static Subject loginUser(String principal, char[] password) throws LoginException, IOException
{
  Subject subject = new Subject();
  LoginContext lc = new LoginContext(com.datatorrent.stram.security.KerberosAuth.class.getName(), subject, new AuthenticationHandler(principal, password), new KerberosConfiguration(principal));
  lc.login();
  return subject;
  //return UserGroupInformation.getUGIFromTicketCache(ticketCache, principal);
}
 
Example 23
Source Project: hadoop   Source File: RegistryTestHelper.java    License: 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 24
Source Project: quarkus-http   Source File: KerberosKDCUtil.java    License: Apache License 2.0 5 votes vote down vote up
static Subject login(final String userName, final char[] password) throws LoginException {
    Subject theSubject = new Subject();
    CallbackHandler cbh = new UsernamePasswordCBH(userName, password);
    LoginContext lc = new LoginContext("KDC", theSubject, cbh, createJaasConfiguration());
    lc.login();

    return theSubject;
}
 
Example 25
Source Project: gcp-token-broker   Source File: SpnegoAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
private Subject principalLogin(String principal, File keytabFile) {
    try {
        LoginContext loginContext = new LoginContext(
                "", new Subject(), null, getConfiguration(principal, keytabFile));
        loginContext.login();
        return loginContext.getSubject();
    } catch (LoginException e) {
        throw new RuntimeException("Failed login for principal `" + principal + "` with keytab `" + keytabFile.getPath() + "`. Error message: " + e.getMessage());
    }
}
 
Example 26
Source Project: openjdk-jdk8u-backup   Source File: LCTest.java    License: 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 27
Source Project: qpid-broker-j   Source File: KerberosUtilities.java    License: Apache License 2.0 5 votes vote down vote up
private LoginContext createLoginContext(final String serviceName, final Subject subject, final Configuration config)
        throws LoginException
{
    return new LoginContext(serviceName, subject, callbacks -> {
        for (Callback callback : callbacks)
        {
            if (callback instanceof TextOutputCallback)
            {
                LOGGER.error(((TextOutputCallback) callback).getMessage());
            }
        }
    }, config);
}
 
Example 28
public static void main(String[] args) throws Exception {
    try {
        LoginContext lc = new LoginContext(TEST_NAME);
        lc.login();
        throw new RuntimeException("Test Case Failed, did not get "
                + "expected exception");
    } catch (Exception ex) {
        if (ex.getMessage().contains("java.io.IOException: "
                + "Configuration Error:")) {
            System.out.println("Test case passed");
        } else {
            throw new RuntimeException(ex);
        }
    }
}
 
Example 29
Source Project: dragonwell8_jdk   Source File: LCTest.java    License: 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 30
Source Project: hadoop   Source File: KerberosAuthenticationHandler.java    License: 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();
}