List of usage examples for javax.security.auth Subject getPrivateCredentials
public <T> Set<T> getPrivateCredentials(Class<T> c)
From source file:org.keycloak.adapters.jaas.DirectAccessGrantsLoginModule.java
@Override public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) { super.initialize(subject, callbackHandler, sharedState, options); this.scope = (String) options.get(SCOPE_OPTION); // This is used just for logout Iterator<RefreshTokenHolder> iterator = subject.getPrivateCredentials(RefreshTokenHolder.class).iterator(); if (iterator.hasNext()) { refreshToken = iterator.next().refreshToken; }/*w w w.jav a 2 s . c o m*/ }
From source file:org.apache.hadoop.hbase.thrift.TestThriftSpnegoHttpServer.java
private CloseableHttpClient createHttpClient() throws Exception { final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(clientPrincipal, clientKeytab); final Set<Principal> clientPrincipals = clientSubject.getPrincipals(); // Make sure the subject has a principal assertFalse(clientPrincipals.isEmpty()); // Get a TGT for the subject (might have many, different encryption types). The first should // be the default encryption type. Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class); assertFalse(privateCredentials.isEmpty()); KerberosTicket tgt = privateCredentials.iterator().next(); assertNotNull(tgt);// w ww . j a va 2 s .c om // The name of the principal final String clientPrincipalName = clientPrincipals.iterator().next().getName(); return Subject.doAs(clientSubject, new PrivilegedExceptionAction<CloseableHttpClient>() { @Override public CloseableHttpClient run() throws Exception { // Logs in with Kerberos via GSS GSSManager gssManager = GSSManager.getInstance(); // jGSS Kerberos login constant Oid oid = new Oid("1.2.840.113554.1.2.2"); GSSName gssClient = gssManager.createName(clientPrincipalName, GSSName.NT_USER_NAME); GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY); Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build(); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential)); return HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry) .setDefaultCredentialsProvider(credentialsProvider).build(); } }); }
From source file:org.apache.hadoop.hbase.http.TestSpnegoHttpServer.java
@Test public void testAllowedClient() throws Exception { // Create the subject for the client final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(CLIENT_PRINCIPAL, clientKeytab); final Set<Principal> clientPrincipals = clientSubject.getPrincipals(); // Make sure the subject has a principal assertFalse(clientPrincipals.isEmpty()); // Get a TGT for the subject (might have many, different encryption types). The first should // be the default encryption type. Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class); assertFalse(privateCredentials.isEmpty()); KerberosTicket tgt = privateCredentials.iterator().next(); assertNotNull(tgt);// w w w . ja v a2 s . c o m // The name of the principal final String principalName = clientPrincipals.iterator().next().getName(); // Run this code, logged in as the subject (the client) HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() { @Override public HttpResponse run() throws Exception { // Logs in with Kerberos via GSS GSSManager gssManager = GSSManager.getInstance(); // jGSS Kerberos login constant Oid oid = new Oid("1.2.840.113554.1.2.2"); GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME); GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY); HttpClientContext context = HttpClientContext.create(); Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build(); HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).build(); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential)); URL url = new URL(getServerURL(server), "/echo?a=b"); context.setTargetHost(new HttpHost(url.getHost(), url.getPort())); context.setCredentialsProvider(credentialsProvider); context.setAuthSchemeRegistry(authRegistry); HttpGet get = new HttpGet(url.toURI()); return client.execute(get, context); } }); assertNotNull(resp); assertEquals(HttpURLConnection.HTTP_OK, resp.getStatusLine().getStatusCode()); assertEquals("a:b", EntityUtils.toString(resp.getEntity()).trim()); }
From source file:io.druid.security.kerberos.KerberosAuthenticator.java
private String getPrincipalFromRequestNew(HttpServletRequest req) { String authorization = req//w w w . j av a 2s. c o m .getHeader(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.AUTHORIZATION); if (authorization == null || !authorization .startsWith(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE)) { return null; } else { authorization = authorization.substring( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE.length()) .trim(); final Base64 base64 = new Base64(0); final byte[] clientToken = base64.decode(authorization); try { DerInputStream ticketStream = new DerInputStream(clientToken); DerValue[] values = ticketStream.getSet(clientToken.length, true); // see this link for AP-REQ format: https://tools.ietf.org/html/rfc1510#section-5.5.1 for (DerValue value : values) { if (isValueAPReq(value)) { APReq apReq = new APReq(value); Ticket ticket = apReq.ticket; EncryptedData encData = ticket.encPart; int eType = encData.getEType(); // find the server's key EncryptionKey finalKey = null; Subject serverSubj = loginContext.getSubject(); Set<Object> serverCreds = serverSubj.getPrivateCredentials(Object.class); for (Object cred : serverCreds) { if (cred instanceof KeyTab) { KeyTab serverKeyTab = (KeyTab) cred; KerberosPrincipal serverPrincipal = new KerberosPrincipal(this.serverPrincipal); KerberosKey[] serverKeys = serverKeyTab.getKeys(serverPrincipal); for (KerberosKey key : serverKeys) { if (key.getKeyType() == eType) { finalKey = new EncryptionKey(key.getKeyType(), key.getEncoded()); break; } } } } if (finalKey == null) { log.error("Could not find matching key from server creds."); return null; } // decrypt the ticket with the server's key byte[] decryptedBytes = encData.decrypt(finalKey, KeyUsage.KU_TICKET); decryptedBytes = encData.reset(decryptedBytes); EncTicketPart decrypted = new EncTicketPart(decryptedBytes); String clientPrincipal = decrypted.cname.toString(); return clientPrincipal; } } } catch (Exception ex) { Throwables.propagate(ex); } } return null; }
From source file:backtype.storm.security.auth.kerberos.KerberosSaslTransportPlugin.java
public TTransportFactory getServerTransportFactory() throws IOException { // create an authentication callback handler CallbackHandler server_callback_handler = new ServerCallbackHandler(login_conf, storm_conf); // login our principal Subject subject = null; try {//www . j a v a2 s . co m // specify a configuration object to be used Configuration.setConfiguration(login_conf); // now login Login login = new Login(AuthUtils.LOGIN_CONTEXT_SERVER, server_callback_handler); subject = login.getSubject(); } catch (LoginException ex) { LOG.error("Server failed to login in principal:" + ex, ex); throw new RuntimeException(ex); } // check the credential of our principal if (subject.getPrivateCredentials(KerberosTicket.class).isEmpty()) { throw new RuntimeException("Fail to verify user principal with section \"" + AuthUtils.LOGIN_CONTEXT_SERVER + "\" in login configuration file " + login_conf); } String principal = AuthUtils.get(login_conf, AuthUtils.LOGIN_CONTEXT_SERVER, "principal"); LOG.debug("principal:" + principal); KerberosName serviceKerberosName = new KerberosName(principal); String serviceName = serviceKerberosName.getServiceName(); String hostName = serviceKerberosName.getHostName(); Map<String, String> props = new TreeMap<String, String>(); props.put(Sasl.QOP, "auth"); props.put(Sasl.SERVER_AUTH, "false"); // create a transport factory that will invoke our auth callback for digest TSaslServerTransport.Factory factory = new TSaslServerTransport.Factory(); factory.addServerDefinition(KERBEROS, serviceName, hostName, props, server_callback_handler); // create a wrap transport factory so that we could apply user credential during connections TUGIAssumingTransportFactory wrapFactory = new TUGIAssumingTransportFactory(factory, subject); LOG.info("SASL GSSAPI transport factory will be used"); return wrapFactory; }
From source file:org.apache.druid.security.kerberos.KerberosAuthenticator.java
private String getPrincipalFromRequestNew(HttpServletRequest req) { String authorization = req//from w ww . jav a 2s .com .getHeader(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.AUTHORIZATION); if (authorization == null || !authorization .startsWith(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE)) { return null; } else { authorization = authorization.substring( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE.length()) .trim(); final Base64 base64 = new Base64(0); final byte[] clientToken = base64.decode(authorization); try { DerInputStream ticketStream = new DerInputStream(clientToken); DerValue[] values = ticketStream.getSet(clientToken.length, true); // see this link for AP-REQ format: https://tools.ietf.org/html/rfc1510#section-5.5.1 for (DerValue value : values) { if (isValueAPReq(value)) { APReq apReq = new APReq(value); Ticket ticket = apReq.ticket; EncryptedData encData = ticket.encPart; int eType = encData.getEType(); // find the server's key EncryptionKey finalKey = null; Subject serverSubj = loginContext.getSubject(); Set<Object> serverCreds = serverSubj.getPrivateCredentials(Object.class); for (Object cred : serverCreds) { if (cred instanceof KeyTab) { KeyTab serverKeyTab = (KeyTab) cred; KerberosPrincipal kerberosPrincipal = new KerberosPrincipal(serverPrincipal); KerberosKey[] serverKeys = serverKeyTab.getKeys(kerberosPrincipal); for (KerberosKey key : serverKeys) { if (key.getKeyType() == eType) { finalKey = new EncryptionKey(key.getKeyType(), key.getEncoded()); break; } } } } if (finalKey == null) { log.error("Could not find matching key from server creds."); return null; } // decrypt the ticket with the server's key byte[] decryptedBytes = encData.decrypt(finalKey, KeyUsage.KU_TICKET); decryptedBytes = encData.reset(decryptedBytes); EncTicketPart decrypted = new EncTicketPart(decryptedBytes); String clientPrincipal = decrypted.cname.toString(); return clientPrincipal; } } } catch (Exception ex) { Throwables.propagate(ex); } } 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 www . ja v a 2 s. 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.storm.security.auth.kerberos.KerberosSaslTransportPlugin.java
public TTransportFactory getServerTransportFactory() throws IOException { //create an authentication callback handler CallbackHandler server_callback_handler = new ServerCallbackHandler(login_conf, topoConf); //login our principal Subject subject = null; try {/*w w w . j a v a 2 s . c o m*/ //specify a configuration object to be used Configuration.setConfiguration(login_conf); //now login Login login = new Login(AuthUtils.LOGIN_CONTEXT_SERVER, server_callback_handler); subject = login.getSubject(); login.startThreadIfNeeded(); } catch (LoginException ex) { LOG.error("Server failed to login in principal:" + ex, ex); throw new RuntimeException(ex); } //check the credential of our principal if (subject.getPrivateCredentials(KerberosTicket.class).isEmpty()) { throw new RuntimeException("Fail to verify user principal with section \"" + AuthUtils.LOGIN_CONTEXT_SERVER + "\" in login configuration file " + login_conf); } String principal = AuthUtils.get(login_conf, AuthUtils.LOGIN_CONTEXT_SERVER, "principal"); LOG.debug("principal:" + principal); KerberosName serviceKerberosName = new KerberosName(principal); String serviceName = serviceKerberosName.getServiceName(); String hostName = serviceKerberosName.getHostName(); Map<String, String> props = new TreeMap<String, String>(); props.put(Sasl.QOP, "auth"); props.put(Sasl.SERVER_AUTH, "false"); //create a transport factory that will invoke our auth callback for digest TSaslServerTransport.Factory factory = new TSaslServerTransport.Factory(); factory.addServerDefinition(KERBEROS, serviceName, hostName, props, server_callback_handler); //create a wrap transport factory so that we could apply user credential during connections TUGIAssumingTransportFactory wrapFactory = new TUGIAssumingTransportFactory(factory, subject); LOG.info("SASL GSSAPI transport factory will be used"); return wrapFactory; }
From source file:org.apache.hadoop.security.UserGroupInformation.java
/** * Create a UserGroupInformation for the given subject. * This does not change the subject or acquire new credentials. * @param subject the user's subject/* w w w . j a v a2 s . c om*/ */ UserGroupInformation(Subject subject) { this.subject = subject; this.user = subject.getPrincipals(User.class).iterator().next(); this.isKeytab = !subject.getPrivateCredentials(KerberosKey.class).isEmpty(); this.isKrbTkt = !subject.getPrivateCredentials(KerberosTicket.class).isEmpty(); }
From source file:com.buaa.cfs.security.UserGroupInformation.java
/** * Create a UserGroupInformation for the given subject. This does not change the subject or acquire new * credentials./*from w w w .j av a2s . com*/ * * @param subject the user's subject */ UserGroupInformation(Subject subject) { this.subject = subject; this.user = subject.getPrincipals(User.class).iterator().next(); this.isKeytab = !subject.getPrivateCredentials(KeyTab.class).isEmpty(); this.isKrbTkt = !subject.getPrivateCredentials(KerberosTicket.class).isEmpty(); }