Java Code Examples for javax.security.auth.login.LoginContext#login()
The following examples show how to use
javax.security.auth.login.LoginContext#login() .
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: TestKMS.java From hadoop with Apache License 2.0 | 6 votes |
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 2
Source File: DynamicConfigurationTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
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 3
Source File: KrbTicket.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
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 4
Source File: KerberosHelper.java From davmail with GNU General Public License v2.0 | 6 votes |
/** * 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 5
Source File: JaasClient.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) { try { LoginContext lc = new LoginContext(LOGIN_CONTEXT, new MyCallbackHandler()); lc.login(); checkPrincipal(lc, true); lc.logout(); checkPrincipal(lc, false); } catch (LoginException le) { throw new RuntimeException(le); } System.out.println("Test passed."); }
Example 6
Source File: Context.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * 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 7
Source File: JAASConfigSyntaxTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
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 8
Source File: KerberosAuthentication.java From presto with Apache License 2.0 | 5 votes |
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 9
Source File: UnboundSSLUtils.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
static void startServerWithJaas(final SSLEchoServer server, String config) throws LoginException, PrivilegedActionException { LoginContext context = new LoginContext(config); context.login(); System.out.println("Server: successful authentication"); Subject.doAs(context.getSubject(), (PrivilegedExceptionAction<Object>) () -> { SSLEchoServer.startServer(server); return null; }); }
Example 10
Source File: Context.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * 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 11
Source File: UnboundSSLUtils.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
static void startServerWithJaas(final SSLEchoServer server, String config) throws LoginException, PrivilegedActionException { LoginContext context = new LoginContext(config); context.login(); System.out.println("Server: successful authentication"); Subject.doAs(context.getSubject(), (PrivilegedExceptionAction<Object>) () -> { SSLEchoServer.startServer(server); return null; }); }
Example 12
Source File: UnboundSSLUtils.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
static void startServerWithJaas(final SSLEchoServer server, String config) throws LoginException, PrivilegedActionException { LoginContext context = new LoginContext(config); context.login(); System.out.println("Server: successful authentication"); Subject.doAs(context.getSubject(), (PrivilegedExceptionAction<Object>) () -> { SSLEchoServer.startServer(server); return null; }); }
Example 13
Source File: PrincipalSystemPropTest.java From TencentKona-8 with GNU General Public License v2.0 | 4 votes |
private static void runTest(boolean expected, String jaasConfigEntry, String expectedLoginUser, String loginUserBySysProp) { if(loginUserBySysProp != null) { System.setProperty("sun.security.krb5.principal", loginUserBySysProp); } else { System.clearProperty("sun.security.krb5.principal"); } try { LoginContext lc = new LoginContext(jaasConfigEntry, new TextCallbackHandler()); lc.login(); System.out.println(String.format( "Authentication completed with Subject '%s' ", lc.getSubject())); if (!expected) { throw new RuntimeException( "TEST FAILED - JAAS login success isn't expected"); } if(expectedLoginUser != null && !lc.getSubject().getPrincipals() .stream().map(p -> p.getName()).filter( expectedLoginUser :: equals).findFirst() .isPresent()) { throw new RuntimeException(String.format( "TEST FAILED - Login principal is not matched " + "to expected principal '%s'.", expectedLoginUser)); } System.out.println( "TEST PASSED - JAAS login success is expected."); } catch (LoginException ie) { System.out.println(String.format( "Authentication failed with exception: %s", ie.getMessage())); if (expected) { System.out.println( "TEST FAILED - JAAS login failure isn't expected"); throw new RuntimeException(ie); } System.out.println( "TEST PASSED - JAAS login failure is expected."); } }
Example 14
Source File: UserGroupInformation.java From hadoop with Apache License 2.0 | 4 votes |
/** * 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 */ 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; } }
Example 15
Source File: StandardCallbacks.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 4 votes |
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: StandardCallbacks.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
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: StandardCallbacks.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
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: PrincipalSystemPropTest.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
private static void runTest(boolean expected, String jaasConfigEntry, String expectedLoginUser, String loginUserBySysProp) { if(loginUserBySysProp != null) { System.setProperty("sun.security.krb5.principal", loginUserBySysProp); } else { System.clearProperty("sun.security.krb5.principal"); } try { LoginContext lc = new LoginContext(jaasConfigEntry, new TextCallbackHandler()); lc.login(); System.out.println(String.format( "Authentication completed with Subject '%s' ", lc.getSubject())); if (!expected) { throw new RuntimeException( "TEST FAILED - JAAS login success isn't expected"); } if(expectedLoginUser != null && !lc.getSubject().getPrincipals() .stream().map(p -> p.getName()).filter( expectedLoginUser :: equals).findFirst() .isPresent()) { throw new RuntimeException(String.format( "TEST FAILED - Login principal is not matched " + "to expected principal '%s'.", expectedLoginUser)); } System.out.println( "TEST PASSED - JAAS login success is expected."); } catch (LoginException ie) { System.out.println(String.format( "Authentication failed with exception: %s", ie.getMessage())); if (expected) { System.out.println( "TEST FAILED - JAAS login failure isn't expected"); throw new RuntimeException(ie); } System.out.println( "TEST PASSED - JAAS login failure is expected."); } }
Example 19
Source File: StandardCallbacks.java From TencentKona-8 with GNU General Public License v2.0 | 4 votes |
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 20
Source File: TestSecureLogins.java From hadoop with Apache License 2.0 | 4 votes |
@Test public void testServerLogin() throws Throwable { LoginContext loginContext = createLoginContextZookeeperLocalhost(); loginContext.login(); loginContext.logout(); }