javax.security.auth.login.LoginContext Java Examples
The following examples show how to use
javax.security.auth.login.LoginContext.
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: SubjectActions.java From lams with GNU General Public License v2.0 | 6 votes |
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 #2
Source File: TestSecureLogins.java From hadoop with Apache License 2.0 | 6 votes |
@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
Source File: DynamicConfigurationTest.java From openjdk-jdk8u-backup 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 #4
Source File: KerberosConnectionTest.java From calcite-avatica with Apache License 2.0 | 6 votes |
@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
Source File: DynamicConfigurationTest.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
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
Source File: DynamicConfigurationTest.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
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 File: LCTest.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
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
Source File: DynamicConfigurationTest.java From TencentKona-8 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 #9
Source File: DynamicConfigurationTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
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 File: PxfUserGroupInformationTest.java From pxf with Apache License 2.0 | 6 votes |
@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 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 #12
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 #13
Source File: AllPlatforms.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
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 #14
Source File: DynamicConfigurationTest.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
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 #15
Source File: Loader.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
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 #16
Source File: SSLAndKerberosTest.java From atlas with Apache License 2.0 | 6 votes |
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 #17
Source File: GenericPrincipal.java From Tomcat7.0.67 with Apache License 2.0 | 6 votes |
/** * 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'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 #18
Source File: TestSecureRegistry.java From hadoop with Apache License 2.0 | 6 votes |
/** * 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 #19
Source File: GSSUtil.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * 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 #20
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 #21
Source File: JAASConfigSyntaxTest.java From openjdk-jdk8u 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 #22
Source File: PxfUserGroupInformationTest.java From pxf with Apache License 2.0 | 5 votes |
@Test public void testReloginFromKeytabNoValidTGT() throws Exception { assertEquals(1, subject.getPrivateCredentials().size()); // subject has 1 ticket user.setLogin(mockLoginContext); PowerMockito.mockStatic(KerberosUtil.class); when(KerberosUtil.hasKerberosKeyTab(subject)).thenReturn(true); when(KerberosUtil.getKrb5LoginModuleName()).thenReturn("com.sun.security.auth.module.Krb5LoginModule"); // need for login when(mockTGT.getServer()).thenReturn(nonTgtPrincipal); // ticket is not from krbtgt, so not valid ugi = new UserGroupInformation(subject); ugi.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS); // leave user.lastLogin at 0 to simulate old login session = new LoginSession("config", "principal", "keytab", ugi, subject, 1); // train to return another LoginContext when it is constructed during re-login mockAnotherLoginContext = PowerMockito.mock(LoginContext.class); PowerMockito.whenNew(LoginContext.class).withAnyArguments().thenReturn(mockAnotherLoginContext); PxfUserGroupInformation.reloginFromKeytab(serverName, session); assertNotSame(mockLoginContext, user.getLogin()); assertSame(mockAnotherLoginContext, user.getLogin()); assertTrue(user.getLastLogin() > 0); // login timestamp is updated /* subject's non-TGT ticket has been removed, in reality another one would be created by login process, * but we are not mocking it here. */ assertTrue(subject.getPrivateCredentials().isEmpty()); verify(mockLoginContext).logout(); verify(mockAnotherLoginContext).login(); verify(mockTGT).destroy(); // subject's non-TGT ticket has been destroyed }
Example #23
Source File: LCTest.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
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 #24
Source File: PxfUserGroupInformation.java From pxf with Apache License 2.0 | 5 votes |
private static LoginContext newLoginContext(String appName, Subject subject, javax.security.auth.login.Configuration loginConf) throws LoginException { // Temporarily switch the thread's ContextClassLoader to match this // class's classloader, so that we can properly load HadoopLoginModule // from the JAAS libraries. Thread t = Thread.currentThread(); ClassLoader oldCCL = t.getContextClassLoader(); t.setContextClassLoader(UserGroupInformation.HadoopLoginModule.class.getClassLoader()); try { return new LoginContext(appName, subject, null, loginConf); } finally { t.setContextClassLoader(oldCCL); } }
Example #25
Source File: User.java From hadoop with Apache License 2.0 | 5 votes |
public User(String name, AuthenticationMethod authMethod, LoginContext login) { try { shortName = new HadoopKerberosName(name).getShortName(); } catch (IOException ioe) { throw new IllegalArgumentException("Illegal principal name " + name +": " + ioe.toString(), ioe); } fullName = name; this.authMethod = authMethod; this.login = login; }
Example #26
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 #27
Source File: JAASConfigSyntaxTest.java From jdk8u-jdk 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 #28
Source File: Context.java From jdk8u60 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 #29
Source File: KerberosKDCUtil.java From quarkus-http with Apache License 2.0 | 5 votes |
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 #30
Source File: PxfUserGroupInformationTest.java From pxf with Apache License 2.0 | 5 votes |
@Test public void testReloginFromKeytabValidTGTWillExpireSoon() throws Exception { user.setLogin(mockLoginContext); PowerMockito.mockStatic(KerberosUtil.class); when(KerberosUtil.hasKerberosKeyTab(subject)).thenReturn(true); when(KerberosUtil.getKrb5LoginModuleName()).thenReturn("com.sun.security.auth.module.Krb5LoginModule"); // need for login when(mockTGT.getServer()).thenReturn(tgtPrincipal); // TGT validity started 1 hr ago, valid for another 10 mins, we are at 6/7 or 85% > 80% of renew window when(mockTGT.getStartTime()).thenReturn(new Date(nowMs - 3600 * 1000L)); when(mockTGT.getEndTime()).thenReturn(new Date(nowMs + 600 * 1000L)); ugi = new UserGroupInformation(subject); ugi.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS); // leave user.lastLogin at 0 to simulate old login session = new LoginSession("config", "principal", "keytab", ugi, subject, 1); // train to return another LoginContext when it is constructed during re-login mockAnotherLoginContext = PowerMockito.mock(LoginContext.class); PowerMockito.whenNew(LoginContext.class).withAnyArguments().thenReturn(mockAnotherLoginContext); PxfUserGroupInformation.reloginFromKeytab(serverName, session); assertNotSame(mockLoginContext, user.getLogin()); assertSame(mockAnotherLoginContext, user.getLogin()); assertTrue(user.getLastLogin() > 0); // login timestamp is updated verify(mockLoginContext).logout(); verify(mockAnotherLoginContext).login(); }