List of usage examples for javax.security.auth.login LoginContext LoginContext
public LoginContext(String name, CallbackHandler callbackHandler) throws LoginException
From source file:org.apache.activemq.jaas.PropertiesLoginModuleTest.java
public void testLogin() throws LoginException { LoginContext context = new LoginContext("PropertiesLogin", new UserPassHandler("first", "secret")); context.login();/*from w w w . j a v a2 s. c o m*/ Subject subject = context.getSubject(); assertEquals("Should have three principals", 3, subject.getPrincipals().size()); assertEquals("Should have one user principal", 1, subject.getPrincipals(UserPrincipal.class).size()); assertEquals("Should have two group principals", 2, subject.getPrincipals(GroupPrincipal.class).size()); context.logout(); assertEquals("Should have zero principals", 0, subject.getPrincipals().size()); }
From source file:org.apache.activemq.jaas.PropertiesLoginModuleTest.java
public void testLoginReload() throws Exception { File targetPropDir = new File("target/loginReloadTest"); File sourcePropDir = new File("src/test/resources"); File usersFile = new File(targetPropDir, "users.properties"); File groupsFile = new File(targetPropDir, "groups.properties"); //Set up initial properties FileUtils.copyFile(new File(sourcePropDir, "users.properties"), usersFile); FileUtils.copyFile(new File(sourcePropDir, "groups.properties"), groupsFile); LoginContext context = new LoginContext("PropertiesLoginReload", new UserPassHandler("first", "secret")); context.login();/*from www .ja v a 2 s. c o m*/ Subject subject = context.getSubject(); //test initial principals assertEquals("Should have three principals", 3, subject.getPrincipals().size()); assertEquals("Should have one user principal", 1, subject.getPrincipals(UserPrincipal.class).size()); assertEquals("Should have two group principals", 2, subject.getPrincipals(GroupPrincipal.class).size()); context.logout(); assertEquals("Should have zero principals", 0, subject.getPrincipals().size()); //Modify the file and test that the properties are reloaded Thread.sleep(1000); FileUtils.copyFile(new File(sourcePropDir, "usersReload.properties"), usersFile); FileUtils.copyFile(new File(sourcePropDir, "groupsReload.properties"), groupsFile); FileUtils.touch(usersFile); FileUtils.touch(groupsFile); //Use new password to verify users file was reloaded context = new LoginContext("PropertiesLoginReload", new UserPassHandler("first", "secrets")); context.login(); subject = context.getSubject(); //Check that the principals changed assertEquals("Should have three principals", 2, subject.getPrincipals().size()); assertEquals("Should have one user principal", 1, subject.getPrincipals(UserPrincipal.class).size()); assertEquals("Should have one group principals", 1, subject.getPrincipals(GroupPrincipal.class).size()); context.logout(); assertEquals("Should have zero principals", 0, subject.getPrincipals().size()); }
From source file:org.apache.activemq.jaas.PropertiesLoginModuleTest.java
public void testBadUseridLogin() throws Exception { LoginContext context = new LoginContext("PropertiesLogin", new UserPassHandler("BAD", "secret")); try {//w w w . ja v a 2 s . c o m context.login(); fail("Should have thrown a FailedLoginException"); } catch (FailedLoginException doNothing) { } }
From source file:org.apache.activemq.jaas.PropertiesLoginModuleTest.java
public void testBadPWLogin() throws Exception { LoginContext context = new LoginContext("PropertiesLogin", new UserPassHandler("first", "BAD")); try {//from w w w . j a v a 2 s. co m context.login(); fail("Should have thrown a FailedLoginException"); } catch (FailedLoginException doNothing) { } }
From source file:org.apache.atlas.web.filters.AtlasAuthenticationKerberosFilterTest.java
protected Subject loginTestUser() throws LoginException, IOException { LoginContext lc = new LoginContext(TEST_USER_JAAS_SECTION, new CallbackHandler() { @Override//ww w.j av a 2 s .com 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(); }
From source file:org.apache.atlas.web.filters.MetadataAuthenticationKerberosFilterIT.java
protected Subject loginTestUser() throws LoginException, IOException { LoginContext lc = new LoginContext(TEST_USER_JAAS_SECTION, new CallbackHandler() { @Override/* w w w. ja va 2s .c o m*/ public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof PasswordCallback) { PasswordCallback passwordCallback = (PasswordCallback) callbacks[i]; passwordCallback.setPassword(TESTPASS.toCharArray()); } if (callbacks[i] instanceof NameCallback) { NameCallback nameCallback = (NameCallback) callbacks[i]; nameCallback.setName(TESTUSER); } } } }); // attempt authentication lc.login(); return lc.getSubject(); }
From source file:org.apache.catalina.realm.JAASRealm.java
/** * Return the Principal associated with the specified username and * credentials, if there is one; otherwise return <code>null</code>. * * If there are any errors with the JDBC connection, executing * the query or anything we return null (don't authenticate). This * event is also logged, and the connection will be closed so that * a subsequent request will automatically re-open it. * * @param username Username of the Principal to look up * @param credentials Password or other credentials to use in * authenticating this username/*from w w w .j a v a 2s . c o m*/ */ public Principal authenticate(String username, String credentials) { // Establish a LoginContext to use for authentication try { LoginContext loginContext = null; if (appName == null) appName = "Tomcat"; if (log.isDebugEnabled()) log.debug("Authenticating " + appName + " " + username); // What if the LoginModule is in the container class loader ? // ClassLoader ocl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); try { loginContext = new LoginContext(appName, new JAASCallbackHandler(this, username, credentials)); } catch (Throwable e) { log.error(sm.getString("jaasRealm.unexpectedError"), e); return (null); } finally { Thread.currentThread().setContextClassLoader(ocl); } if (log.isDebugEnabled()) log.debug("Login context created " + username); // Negotiate a login via this LoginContext Subject subject = null; try { loginContext.login(); subject = loginContext.getSubject(); if (subject == null) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.failedLogin", username)); return (null); } } catch (AccountExpiredException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.accountExpired", username)); return (null); } catch (CredentialExpiredException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.credentialExpired", username)); return (null); } catch (FailedLoginException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.failedLogin", username)); return (null); } catch (LoginException e) { log.warn(sm.getString("jaasRealm.loginException", username), e); return (null); } catch (Throwable e) { log.error(sm.getString("jaasRealm.unexpectedError"), e); return (null); } if (log.isDebugEnabled()) log.debug("Getting principal " + subject); // Return the appropriate Principal for this authenticated Subject Principal principal = createPrincipal(username, subject); if (principal == null) { log.debug(sm.getString("jaasRealm.authenticateFailure", username)); return (null); } if (log.isDebugEnabled()) { log.debug(sm.getString("jaasRealm.authenticateSuccess", username)); } return (principal); } catch (Throwable t) { log.error("error ", t); return null; } }
From source file:org.apache.coheigea.cxf.kerberos.authentication.TokenPreAuthTest.java
@org.junit.Test public void unitTokenAuthGSSTest() throws Exception { // 1. Get a TGT from the KDC for the client + create an armor cache KrbClient client = new KrbClient(); client.setKdcHost("localhost"); client.setKdcTcpPort(kerbyServer.getKdcPort()); client.setAllowUdp(false);//from w w w . j av a 2s . co m client.setKdcRealm(kerbyServer.getKdcSetting().getKdcRealm()); client.init(); TgtTicket tgt = client.requestTgt("alice@service.ws.apache.org", "alice"); assertNotNull(tgt); // Write to cache Credential credential = new Credential(tgt); CredentialCache cCache = new CredentialCache(); cCache.addCredential(credential); cCache.setPrimaryPrincipal(tgt.getClientPrincipal()); File cCacheFile = File.createTempFile("krb5_alice@service.ws.apache.org", "cc"); cCache.store(cCacheFile); // Now read in JAAS config + substitute in the armor cache file path value String basedir = System.getProperty("basedir"); if (basedir == null) { basedir = new File(".").getCanonicalPath(); } File f = new File(basedir + "/target/test-classes/kerberos/kerberos.jaas"); FileInputStream inputStream = new FileInputStream(f); String content = IOUtils.toString(inputStream, "UTF-8"); inputStream.close(); content = content.replaceAll("armorCacheVal", cCacheFile.getPath()); File f2 = new File(basedir + "/target/test-classes/kerberos/kerberos.jaas"); FileOutputStream outputStream = new FileOutputStream(f2); IOUtils.write(content, outputStream, "UTF-8"); outputStream.close(); // 2. Create a JWT token using CXF JwtClaims claims = new JwtClaims(); claims.setSubject("alice"); claims.setIssuer("DoubleItSTSIssuer"); claims.setIssuedAt(new Date().getTime() / 1000L); claims.setExpiryTime(new Date().getTime() + (60L + 1000L)); String address = "krbtgt/service.ws.apache.org@service.ws.apache.org"; claims.setAudiences(Collections.singletonList(address)); KeyStore keystore = KeyStore.getInstance("JKS"); keystore.load(Loader.getResourceAsStream("clientstore.jks"), "cspass".toCharArray()); Properties signingProperties = new Properties(); signingProperties.put(JoseConstants.RSSEC_SIGNATURE_ALGORITHM, SignatureAlgorithm.RS256.name()); signingProperties.put(JoseConstants.RSSEC_KEY_STORE, keystore); signingProperties.put(JoseConstants.RSSEC_KEY_STORE_ALIAS, "myclientkey"); signingProperties.put(JoseConstants.RSSEC_KEY_PSWD, "ckpass"); JwsHeaders jwsHeaders = new JwsHeaders(signingProperties); JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims); JwsSignatureProvider sigProvider = JwsUtils.loadSignatureProvider(signingProperties, jwsHeaders); String signedToken = jws.signWith(sigProvider); // Store the JWT token in the token cache File tokenCache = new File(basedir + "/target/tokencache.txt"); if (!tokenCache.exists()) { tokenCache.createNewFile(); } TokenCache.writeToken(signedToken, tokenCache.getPath()); // 3. Now log in using JAAS LoginContext loginContext = new LoginContext("aliceTokenAuth", new KerberosCallbackHandler()); loginContext.login(); Subject clientSubject = loginContext.getSubject(); //Set<Principal> clientPrincipals = clientSubject.getPrincipals(); //assertFalse(clientPrincipals.isEmpty()); // Get the TGT Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class); assertFalse(privateCredentials.isEmpty()); // Get the service ticket using GSS KerberosClientExceptionAction action = new KerberosClientExceptionAction( new KerberosPrincipal("alice@service.ws.apache.org"), "bob@service.ws.apache.org"); byte[] ticket = (byte[]) Subject.doAs(clientSubject, action); assertNotNull(ticket); loginContext.logout(); validateServiceTicket(ticket); cCacheFile.delete(); tokenCache.delete(); }
From source file:org.apache.coheigea.cxf.kerberos.authentication.TokenPreAuthTest.java
private void validateServiceTicket(byte[] ticket) throws Exception { // Get the TGT for the service LoginContext loginContext = new LoginContext("bob", new KerberosCallbackHandler()); loginContext.login();//ww w.j ava2s.c o m Subject serviceSubject = loginContext.getSubject(); Set<Principal> servicePrincipals = serviceSubject.getPrincipals(); assertFalse(servicePrincipals.isEmpty()); // Handle the service ticket KerberosServiceExceptionAction serviceAction = new KerberosServiceExceptionAction(ticket, "bob@service.ws.apache.org"); Subject.doAs(serviceSubject, serviceAction); }
From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java
private void doGssapiBind(final InnerRunnable innerRunnable) throws NamingException { File configFile = null;//www. j a v a 2s . com try { Preferences preferences = ConnectionCorePlugin.getDefault().getPluginPreferences(); boolean useKrb5SystemProperties = preferences .getBoolean(ConnectionCoreConstants.PREFERENCE_USE_KRB5_SYSTEM_PROPERTIES); String krb5LoginModule = preferences.getString(ConnectionCoreConstants.PREFERENCE_KRB5_LOGIN_MODULE); if (!useKrb5SystemProperties) { // Kerberos Configuration switch (connection.getConnectionParameter().getKrb5Configuration()) { case DEFAULT: // nothing System.clearProperty("java.security.krb5.conf"); //$NON-NLS-1$ break; case FILE: // use specified krb5.conf System.setProperty("java.security.krb5.conf", connection.getConnectionParameter() //$NON-NLS-1$ .getKrb5ConfigurationFile()); break; case MANUAL: // write manual config parameters to connection specific krb5.conf file String fileName = Utils.getFilenameString(connection.getId()) + ".krb5.conf"; //$NON-NLS-1$ configFile = ConnectionCorePlugin.getDefault().getStateLocation().append(fileName).toFile(); String realm = connection.getConnectionParameter().getKrb5Realm(); String host = connection.getConnectionParameter().getKrb5KdcHost(); int port = connection.getConnectionParameter().getKrb5KdcPort(); StringBuilder sb = new StringBuilder(); sb.append("[libdefaults]").append(ConnectionCoreConstants.LINE_SEPARATOR); //$NON-NLS-1$ sb.append("default_realm = ").append(realm).append(ConnectionCoreConstants.LINE_SEPARATOR); //$NON-NLS-1$ sb.append("[realms]").append(ConnectionCoreConstants.LINE_SEPARATOR); //$NON-NLS-1$ sb.append(realm).append(" = {").append(ConnectionCoreConstants.LINE_SEPARATOR); //$NON-NLS-1$ sb.append("kdc = ").append(host).append(":").append(port).append( //$NON-NLS-1$ //$NON-NLS-2$ ConnectionCoreConstants.LINE_SEPARATOR); sb.append("}").append(ConnectionCoreConstants.LINE_SEPARATOR); //$NON-NLS-1$ try { FileUtils.writeStringToFile(configFile, sb.toString()); } catch (IOException ioe) { NamingException ne = new NamingException(); ne.setRootCause(ioe); throw ne; } System.setProperty("java.security.krb5.conf", configFile.getAbsolutePath()); //$NON-NLS-1$ } // Use our custom configuration so we don't need to mess with external configuration Configuration.setConfiguration(new InnerConfiguration(krb5LoginModule)); } // Gets the TGT, either from native ticket cache or obtain new from KDC LoginContext lc = null; try { lc = new LoginContext(this.getClass().getName(), new InnerCallbackHandler()); lc.login(); } catch (LoginException le) { NamingException ne = new NamingException(); ne.setRootCause(le); throw ne; } // Login to LDAP server, obtains a service ticket from KDC Subject.doAs(lc.getSubject(), (PrivilegedAction<Object>) () -> { try { context.reconnect(context.getConnectControls()); } catch (NamingException ne) { innerRunnable.namingException = ne; } return null; }); } finally { // delete temporary config file if (configFile != null && configFile.exists()) { configFile.delete(); } } }