Refine search
URLEncoder.encode(doAsUser, "UTF-8")); String urlStr = url.toExternalForm(); StringBuilder sb = new StringBuilder(urlStr); String separator = (urlStr.contains("?")) ? "&" : "?"; separator = "&"; url = new URL(sb.toString()); AuthenticatedURL aUrl = new AuthenticatedURL(this, connConfigurator); org.apache.hadoop.security.token.Token<AbstractDelegationTokenIdentifier> dt = null; HttpURLConnection conn = aUrl.openConnection(url, token); conn.setRequestMethod(operation.getHttpMethod()); HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_OK); if (hasResponse) { String contentType = conn.getHeaderField(CONTENT_TYPE); contentType = (contentType != null) ? StringUtils.toLowerCase(contentType) : null; contentType.contains(APPLICATION_JSON_MIME)) { try { ret = JsonSerialization.mapReader().readValue(conn.getInputStream()); } catch (Exception ex) { throw new AuthenticationException(String.format( "'%s' did not handle the '%s' delegation token operation: %s", url.getAuthority(), operation, ex.getMessage()), ex);
/** Gets the Hadoop kerberos secure connection (not an SSL connection). */ private HttpURLConnection getSecureConnection(URL url) throws IOException { AuthenticatedURL.Token token = new AuthenticatedURL.Token(); try { return new AuthenticatedURL().openConnection(url, token); } catch (AuthenticationException e) { throw new IOException(e); } }
public static HttpURLConnection loginAuthenticatedURL(final URL url, final String keytabPrincipal, final String keytabPath) throws Exception { final List<URL> resources = new ArrayList<>(); resources.add(url); final URLClassLoader ucl = new URLClassLoader(resources.toArray(new URL[resources.size()])); final Configuration conf = new Configuration(); conf.setClassLoader(ucl); UserGroupInformation.setConfiguration(conf); logger.info( "Logging in URL: " + url.toString() + " using Principal: " + keytabPrincipal + ", Keytab: " + keytabPath); UserGroupInformation.loginUserFromKeytab(keytabPrincipal, keytabPath); final HttpURLConnection connection = UserGroupInformation.getLoginUser().doAs( (PrivilegedExceptionAction<HttpURLConnection>) () -> { final Token token = new Token(); return new AuthenticatedURL().openConnection(url, token); }); return connection; } }
AuthenticatedURL.Token token = new AuthenticatedURL.Token(); AuthenticatedURL aUrl; SSLFactory clientSslFactory; URLConnection connection; if (PROTOCOL_HTTPS.equals(url.getProtocol())) { clientSslFactory = new SSLFactory( SSLFactory.Mode.CLIENT, this.getConf()); SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory(); aUrl = new AuthenticatedURL( new KerberosAuthenticator(), clientSslFactory); connection = aUrl.openConnection(url, token); HttpsURLConnection httpsConn = (HttpsURLConnection) connection; httpsConn.setSSLSocketFactory(sslSocketF); } else { aUrl = new AuthenticatedURL(new KerberosAuthenticator()); connection = aUrl.openConnection(url, token);
/** * Performs simple authentication against the specified URL. * <p> * If a token is given it does a NOP and returns the given token. * <p> * If no token is given, it will perform an HTTP <code>OPTIONS</code> request injecting an additional * parameter {@link #USER_NAME} in the query string with the value returned by the {@link #getUserName()} * method. * <p> * If the response is successful it will update the authentication token. * * @param url the URl to authenticate against. * @param token the authentication token being used for the user. * * @throws IOException if an IO error occurred. * @throws AuthenticationException if an authentication error occurred. */ @Override public void authenticate(URL url, AuthenticatedURL.Token token) throws IOException, AuthenticationException { String strUrl = url.toString(); String paramSeparator = (strUrl.contains("?")) ? "&" : "?"; strUrl += paramSeparator + USER_NAME_EQ + getUserName(); url = new URL(strUrl); HttpURLConnection conn = token.openConnection(url, connConfigurator); conn.setRequestMethod("OPTIONS"); conn.connect(); AuthenticatedURL.extractToken(conn, token); }
@Test public void testConnectionConfigurator() throws Exception { HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); Mockito.when(conn.getResponseCode()). thenReturn(HttpURLConnection.HTTP_UNAUTHORIZED); ConnectionConfigurator connConf = Mockito.mock(ConnectionConfigurator.class); Mockito.when(connConf.configure(Mockito.<HttpURLConnection>any())). thenReturn(conn); Authenticator authenticator = Mockito.mock(Authenticator.class); AuthenticatedURL aURL = new AuthenticatedURL(authenticator, connConf); aURL.openConnection(new URL("http://foo"), new AuthenticatedURL.Token()); Mockito.verify(connConf).configure(Mockito.<HttpURLConnection>any()); }
protected void _testAuthentication(Authenticator authenticator, boolean doPost) throws Exception { start(); try { URL url = new URL(getBaseURL()); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); Assert.assertFalse(token.isSet()); TestConnectionConfigurator connConf = new TestConnectionConfigurator(); AuthenticatedURL aUrl = new AuthenticatedURL(authenticator, connConf); HttpURLConnection conn = aUrl.openConnection(url, token); Assert.assertTrue(connConf.invoked); String tokenStr = token.toString(); if (doPost) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.connect(); if (doPost) { Writer writer = new OutputStreamWriter(conn.getOutputStream()); Assert.assertNull(reader.readLine()); aUrl = new AuthenticatedURL(); conn = aUrl.openConnection(url, token); conn.connect(); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
public void authenticate(URL url, AuthenticatedURL.Token token) throws IOException, AuthenticationException { if (!token.isSet()) { this.url = url; base64 = new Base64(0); conn = (HttpURLConnection) url.openConnection(); if (connConfigurator != null) { conn = connConfigurator.configure(conn); conn.setRequestMethod(AUTH_HTTP_METHOD); conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { LOG.debug("JDK performed authentication on our behalf."); AuthenticatedURL.extractToken(conn, token); return; } else if (isNegotiate()) {
@Test public void testPingWithoutSubject() throws Exception { final URL url = new URL("http://"+ SERVER_HOST + ":" + webServerPort + "/ping"); try { new AuthenticatedURL(new KerberosAuthenticator()).openConnection(url, new AuthenticatedURL.Token()); fail("Here should fail."); } catch (Exception e) { boolean isExpectError = e.getMessage().contains("No valid credentials provided"); Assert.assertTrue("Here should fail by 'No valid credentials provided'," + " but the exception is:" + e, isExpectError); } }
/** * Returns an authenticated {@link HttpURLConnection}. * * @param url the URL to connect to. Only HTTP/S URLs are supported. * @param token the authentication token being used for the user. * * @return an authenticated {@link HttpURLConnection}. * * @throws IOException if an IO error occurred. * @throws AuthenticationException if an authentication exception occurred. */ public HttpURLConnection openConnection(URL url, Token token) throws IOException, AuthenticationException { if (url == null) { throw new IllegalArgumentException("url cannot be NULL"); } if (!url.getProtocol().equalsIgnoreCase("http") && !url.getProtocol().equalsIgnoreCase("https")) { throw new IllegalArgumentException("url must be for a HTTP or HTTPS resource"); } if (token == null) { throw new IllegalArgumentException("token cannot be NULL"); } authenticator.authenticate(url, token); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (connConfigurator != null) { conn = connConfigurator.configure(conn); } injectToken(conn, token); return conn; }
try { if (jsonOutput != null) { writeJson(jsonOutput, conn.getOutputStream()); conn.getInputStream().close(); throw ex; if ((conn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN && (conn.getResponseMessage().equals(ANONYMOUS_REQUESTS_DISALLOWED) || conn.getResponseMessage().contains(INVALID_SIGNATURE))) AuthenticatedURL.extractToken(conn, authToken); } catch (AuthenticationException e) {
currentToken = new AuthenticatedURL.Token(); } else { currentToken = new AuthenticatedURL.Token(readToken.toString()); if (currentToken.isSet()) { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("OPTIONS"); AuthenticatedURL.injectToken(conn, currentToken); if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED || conn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) { if (useAuthFile) { AUTH_TOKEN_CACHE_FILE.delete(); AuthenticatedURL.extractToken(conn, currentToken); } catch (AuthenticationException ex) { if (useAuthFile) { AuthenticatedURL.injectToken(conn, currentToken); return conn;
final AuthenticatedURL.Token authToken = new AuthenticatedURL.Token(); return new AuthenticatedURL(new KerberosUgiAuthenticator(), connConfigurator).openConnection(url, authToken); } else { if (LOG.isDebugEnabled()) { LOG.debug("open URL connection"); URLConnection connection = url.openConnection(); if (connection instanceof HttpURLConnection) { connConfigurator.configure((HttpURLConnection) connection);
URL url = new URL("http://youhost:8080/your-kerberised-resource"); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); HttpURLConnection conn = new AuthenticatedURL().openConnection(url, token); String authorizationTokenString = conn.getRequestProperty("Authorization"); String delegationToken = conn.getRequestProperty("X-Hadoop-Delegation-Token"); ... // do what you have to to get your basic client connection ... myBasicClientConnection.setRequestProperty("Authorization", authorizationTokenString); myBasicClientConnection.setRequestProperty("Cookie", "hadoop.auth=" + token.toString()); myBasicClientConnection.setRequestProperty("X-Hadoop-Delegation-Token", delegationToken);
getCredentials(); if (!creds.getAllTokens().isEmpty()) { InetSocketAddress serviceAddr = new InetSocketAddress(url.getHost(), url.getPort()); Text service = SecurityUtil.buildTokenService(serviceAddr); dToken = creds.getToken(service); HttpURLConnection conn = super.openConnection(url, token); if (!token.isSet() && !useQueryStringForDelegationToken() && dToken != null) { conn.setRequestProperty( DelegationTokenAuthenticator.DELEGATION_TOKEN_HEADER, dToken.encodeToUrlString());
@Test public void testExtractTokenOK() throws Exception { HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); String tokenStr = "foo"; Map<String, List<String>> headers = new HashMap<String, List<String>>(); List<String> cookies = new ArrayList<String>(); cookies.add(AuthenticatedURL.AUTH_COOKIE + "=" + tokenStr); headers.put("Set-Cookie", cookies); Mockito.when(conn.getHeaderFields()).thenReturn(headers); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); AuthenticatedURL.extractToken(conn, token); Assert.assertEquals(tokenStr, token.toString()); }
private static HttpURLConnection getConnection(URL url) throws IOException { AuthenticatedURL.Token token = new AuthenticatedURL.Token(); HttpURLConnection conn; try { conn = new AuthenticatedURL(AuthenticatorClass.newInstance()).openConnection(url, token); } catch (AuthenticationException | InstantiationException | IllegalAccessException ex) { throw new IOException("Could not authenticate, " + ex.getMessage(), ex); } if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Unexpected response code [" + conn.getResponseCode() + "], message [" + conn.getResponseMessage() + "]"); } return conn; }
HttpURLConnection conn = super.openConnection(url, token); if (!token.isSet() && !useQueryStringForDelegationToken() && dToken != null) { conn.setRequestProperty( DelegationTokenAuthenticator.DELEGATION_TOKEN_HEADER, dToken.encodeToUrlString());
@Test public void testInjectToken() throws Exception { HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); token.set("foo"); AuthenticatedURL.injectToken(conn, token); Mockito.verify(conn).addRequestProperty(Mockito.eq("Cookie"), Mockito.anyString()); }
@Test public void testPing() throws Exception { SentryServiceIntegrationBase.clientUgi.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { final URL url = new URL("http://"+ SentryServiceIntegrationBase.SERVER_HOST + ":" + SentryServiceIntegrationBase.webServerPort + "/ping"); HttpURLConnection conn = new AuthenticatedURL(new KerberosAuthenticator()). openConnection(url, new AuthenticatedURL.Token()); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); String response = IOUtils.toString(conn.getInputStream()); Assert.assertEquals("pong\n", response); return null; }} ); }