Search in sources :

Example 61 with Route

use of okhttp3.Route in project github-oauth-plugin by jenkinsci.

the class JenkinsProxyAuthenticator method authenticate.

@CheckForNull
@Override
public Request authenticate(@CheckForNull Route route, @NonNull Response response) {
    if (response.request().header("Proxy-Authorization") != null) {
        // Give up since we already tried to authenticate
        return null;
    }
    if (response.challenges().isEmpty()) {
        // Proxy does not require authentication
        return null;
    }
    // Refuse pre-emptive challenge
    if (response.challenges().size() == 1) {
        Challenge challenge = response.challenges().get(0);
        if (challenge.scheme().equalsIgnoreCase("OkHttp-Preemptive")) {
            return null;
        }
    }
    for (Challenge challenge : response.challenges()) {
        if (challenge.scheme().equalsIgnoreCase("Basic")) {
            String username = proxy.getUserName();
            Secret password = proxy.getSecretPassword();
            if (username != null && password != null) {
                String credentials = Credentials.basic(username, password.getPlainText());
                return response.request().newBuilder().header("Proxy-Authorization", credentials).build();
            } else {
                LOGGER.log(Level.WARNING, "Proxy requires Basic authentication but no username and password have been configured for the proxy");
            }
            break;
        }
    }
    LOGGER.log(Level.WARNING, "Proxy requires authentication, but does not support Basic authentication");
    return null;
}
Also used : Secret(hudson.util.Secret) Challenge(okhttp3.Challenge) CheckForNull(edu.umd.cs.findbugs.annotations.CheckForNull)

Example 62 with Route

use of okhttp3.Route in project trino by trinodb.

the class TestResourceSecurity method testOAuth2Groups.

@Test(dataProvider = "groups")
public void testOAuth2Groups(Optional<Set<String>> groups) throws Exception {
    try (TokenServer tokenServer = new TokenServer(Optional.empty());
        TestingTrinoServer server = TestingTrinoServer.builder().setProperties(ImmutableMap.<String, String>builder().putAll(SECURE_PROPERTIES).put("web-ui.enabled", "true").put("http-server.authentication.type", "oauth2").putAll(getOAuth2Properties(tokenServer)).put("http-server.authentication.oauth2.groups-field", GROUPS_CLAIM).buildOrThrow()).setAdditionalModule(oauth2Module(tokenServer)).build()) {
        server.getInstance(Key.get(AccessControlManager.class)).addSystemAccessControl(TestSystemAccessControl.NO_IMPERSONATION);
        HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
        String accessToken = tokenServer.issueAccessToken(groups);
        OkHttpClient clientWithOAuthToken = client.newBuilder().authenticator((route, response) -> response.request().newBuilder().header(AUTHORIZATION, "Bearer " + accessToken).build()).build();
        assertAuthenticationAutomatic(httpServerInfo.getHttpsUri(), clientWithOAuthToken);
        try (Response response = clientWithOAuthToken.newCall(new Request.Builder().url(getLocation(httpServerInfo.getHttpsUri(), "/protocol/identity")).build()).execute()) {
            assertEquals(response.code(), SC_OK);
            assertEquals(response.header("user"), TEST_USER);
            assertEquals(response.header("principal"), TEST_USER);
            assertEquals(response.header("groups"), groups.map(TestResource::toHeader).orElse(""));
        }
        OkHttpClient clientWithOAuthCookie = client.newBuilder().cookieJar(new CookieJar() {

            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
            }

            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                return ImmutableList.of(new Cookie.Builder().domain(httpServerInfo.getHttpsUri().getHost()).path(UI_LOCATION).name(OAUTH2_COOKIE).value(accessToken).httpOnly().secure().build());
            }
        }).build();
        try (Response response = clientWithOAuthCookie.newCall(new Request.Builder().url(getLocation(httpServerInfo.getHttpsUri(), "/ui/api/identity")).build()).execute()) {
            assertEquals(response.code(), SC_OK);
            assertEquals(response.header("user"), TEST_USER);
            assertEquals(response.header("principal"), TEST_USER);
            assertEquals(response.header("groups"), groups.map(TestResource::toHeader).orElse(""));
        }
    }
}
Also used : AccessDeniedException.denyReadSystemInformationAccess(io.trino.spi.security.AccessDeniedException.denyReadSystemInformationAccess) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) AccessControlManager(io.trino.security.AccessControlManager) ZonedDateTime(java.time.ZonedDateTime) NodeInfo(io.airlift.node.NodeInfo) Test(org.testng.annotations.Test) HttpServerConfig(io.airlift.http.server.HttpServerConfig) SystemSecurityContext(io.trino.spi.security.SystemSecurityContext) JwsHeader(io.jsonwebtoken.JwsHeader) HttpCookie(java.net.HttpCookie) Matcher(java.util.regex.Matcher) JwtBuilder(io.jsonwebtoken.JwtBuilder) Map(java.util.Map) Path(java.nio.file.Path) Assert.assertEquals(io.trino.testing.assertions.Assert.assertEquals) PemReader(io.airlift.security.pem.PemReader) CookieJar(okhttp3.CookieJar) Request(okhttp3.Request) HttpServlet(javax.servlet.http.HttpServlet) SET_COOKIE(javax.ws.rs.core.HttpHeaders.SET_COOKIE) JavaNetCookieJar(okhttp3.JavaNetCookieJar) Set(java.util.Set) PreparedStatementEncoder(io.trino.server.protocol.PreparedStatementEncoder) BasicPrincipal(io.trino.spi.security.BasicPrincipal) HttpServerInfo(io.airlift.http.server.HttpServerInfo) AccessControl(io.trino.security.AccessControl) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) ProtocolConfig(io.trino.server.ProtocolConfig) AccessDeniedException(io.trino.spi.security.AccessDeniedException) NONCE(io.trino.server.security.oauth2.OAuth2Service.NONCE) GET(javax.ws.rs.GET) OkHttpUtil.setupSsl(io.trino.client.OkHttpUtil.setupSsl) MINUTES(java.util.concurrent.TimeUnit.MINUTES) LOCATION(javax.ws.rs.core.HttpHeaders.LOCATION) HttpServletRequest(javax.servlet.http.HttpServletRequest) Identity(io.trino.spi.security.Identity) Response(okhttp3.Response) SC_UNAUTHORIZED(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED) Resources(com.google.common.io.Resources) Files(java.nio.file.Files) IOException(java.io.IOException) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) File(java.io.File) WWW_AUTHENTICATE(javax.ws.rs.core.HttpHeaders.WWW_AUTHENTICATE) OkHttpClient(okhttp3.OkHttpClient) ChronoUnit(java.time.temporal.ChronoUnit) Paths(java.nio.file.Paths) OAUTH2_COOKIE(io.trino.server.ui.OAuthWebUiCookie.OAUTH2_COOKIE) AllowAllSystemAccessControl(io.trino.plugin.base.security.AllowAllSystemAccessControl) Module(com.google.inject.Module) AUTHENTICATED_USER(io.trino.server.security.ResourceSecurity.AccessType.AUTHENTICATED_USER) Date(java.util.Date) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Key(com.google.inject.Key) AUTHORIZATION(com.google.common.net.HttpHeaders.AUTHORIZATION) SC_SEE_OTHER(javax.servlet.http.HttpServletResponse.SC_SEE_OTHER) URI(java.net.URI) WEB_UI(io.trino.server.security.ResourceSecurity.AccessType.WEB_UI) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer) OptionalBinder.newOptionalBinder(com.google.inject.multibindings.OptionalBinder.newOptionalBinder) ImmutableSet(com.google.common.collect.ImmutableSet) Context(javax.ws.rs.core.Context) ImmutableMap(com.google.common.collect.ImmutableMap) BeforeClass(org.testng.annotations.BeforeClass) Assert.assertNotNull(org.testng.Assert.assertNotNull) Credentials(okhttp3.Credentials) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) Base64(java.util.Base64) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Principal(java.security.Principal) CookieManager(java.net.CookieManager) SC_OK(javax.servlet.http.HttpServletResponse.SC_OK) HttpUriBuilder.uriBuilderFrom(io.airlift.http.client.HttpUriBuilder.uriBuilderFrom) JaxrsBinder.jaxrsBinder(io.airlift.jaxrs.JaxrsBinder.jaxrsBinder) MetadataManager.createTestMetadataManager(io.trino.metadata.MetadataManager.createTestMetadataManager) Optional(java.util.Optional) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) Pattern(java.util.regex.Pattern) HttpUrl(okhttp3.HttpUrl) Instant.now(java.time.Instant.now) DataProvider(org.testng.annotations.DataProvider) JwtUtil.newJwtBuilder(io.trino.server.security.jwt.JwtUtil.newJwtBuilder) OAuth2Client(io.trino.server.security.oauth2.OAuth2Client) Headers(okhttp3.Headers) AtomicReference(java.util.concurrent.atomic.AtomicReference) Inject(javax.inject.Inject) Cookie(okhttp3.Cookie) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) HttpRequestSessionContextFactory(io.trino.server.HttpRequestSessionContextFactory) UI_LOCATION(io.trino.server.ui.FormWebUiAuthenticationFilter.UI_LOCATION) TestingHttpServer(io.airlift.http.server.testing.TestingHttpServer) Keys.hmacShaKeyFor(io.jsonwebtoken.security.Keys.hmacShaKeyFor) AccessDeniedException.denyImpersonateUser(io.trino.spi.security.AccessDeniedException.denyImpersonateUser) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) SC_FORBIDDEN(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN) Assert.assertTrue(org.testng.Assert.assertTrue) TRINO_HEADERS(io.trino.client.ProtocolHeaders.TRINO_HEADERS) HttpCookie(java.net.HttpCookie) Cookie(okhttp3.Cookie) OkHttpClient(okhttp3.OkHttpClient) JwtBuilder(io.jsonwebtoken.JwtBuilder) JwtUtil.newJwtBuilder(io.trino.server.security.jwt.JwtUtil.newJwtBuilder) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) CookieJar(okhttp3.CookieJar) JavaNetCookieJar(okhttp3.JavaNetCookieJar) HttpServerInfo(io.airlift.http.server.HttpServerInfo) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer) Test(org.testng.annotations.Test)

Example 63 with Route

use of okhttp3.Route in project trino by trinodb.

the class TestResourceSecurity method testJwtAndOAuth2AuthenticatorsSeparation.

@Test
public void testJwtAndOAuth2AuthenticatorsSeparation() throws Exception {
    TestingHttpServer jwkServer = createTestingJwkServer();
    jwkServer.start();
    try (TokenServer tokenServer = new TokenServer(Optional.empty());
        TestingTrinoServer server = TestingTrinoServer.builder().setProperties(ImmutableMap.<String, String>builder().putAll(SECURE_PROPERTIES).put("http-server.authentication.type", "jwt,oauth2").put("http-server.authentication.jwt.key-file", jwkServer.getBaseUrl().toString()).putAll(getOAuth2Properties(tokenServer)).put("web-ui.enabled", "true").buildOrThrow()).setAdditionalModule(oauth2Module(tokenServer)).build()) {
        server.getInstance(Key.get(AccessControlManager.class)).addSystemAccessControl(TestSystemAccessControl.NO_IMPERSONATION);
        HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
        assertAuthenticationDisabled(httpServerInfo.getHttpUri());
        OkHttpClient clientWithOAuthToken = client.newBuilder().authenticator((route, response) -> response.request().newBuilder().header(AUTHORIZATION, "Bearer " + tokenServer.getAccessToken()).build()).build();
        assertAuthenticationAutomatic(httpServerInfo.getHttpsUri(), clientWithOAuthToken);
        String token = newJwtBuilder().signWith(JWK_PRIVATE_KEY).setHeaderParam(JwsHeader.KEY_ID, JWK_KEY_ID).setSubject("test-user").setExpiration(Date.from(ZonedDateTime.now().plusMinutes(5).toInstant())).compact();
        OkHttpClient clientWithJwt = client.newBuilder().authenticator((route, response) -> response.request().newBuilder().header(AUTHORIZATION, "Bearer " + token).build()).build();
        assertAuthenticationAutomatic(httpServerInfo.getHttpsUri(), clientWithJwt);
    }
}
Also used : AccessDeniedException.denyReadSystemInformationAccess(io.trino.spi.security.AccessDeniedException.denyReadSystemInformationAccess) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) AccessControlManager(io.trino.security.AccessControlManager) ZonedDateTime(java.time.ZonedDateTime) NodeInfo(io.airlift.node.NodeInfo) Test(org.testng.annotations.Test) HttpServerConfig(io.airlift.http.server.HttpServerConfig) SystemSecurityContext(io.trino.spi.security.SystemSecurityContext) JwsHeader(io.jsonwebtoken.JwsHeader) HttpCookie(java.net.HttpCookie) Matcher(java.util.regex.Matcher) JwtBuilder(io.jsonwebtoken.JwtBuilder) Map(java.util.Map) Path(java.nio.file.Path) Assert.assertEquals(io.trino.testing.assertions.Assert.assertEquals) PemReader(io.airlift.security.pem.PemReader) CookieJar(okhttp3.CookieJar) Request(okhttp3.Request) HttpServlet(javax.servlet.http.HttpServlet) SET_COOKIE(javax.ws.rs.core.HttpHeaders.SET_COOKIE) JavaNetCookieJar(okhttp3.JavaNetCookieJar) Set(java.util.Set) PreparedStatementEncoder(io.trino.server.protocol.PreparedStatementEncoder) BasicPrincipal(io.trino.spi.security.BasicPrincipal) HttpServerInfo(io.airlift.http.server.HttpServerInfo) AccessControl(io.trino.security.AccessControl) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) ProtocolConfig(io.trino.server.ProtocolConfig) AccessDeniedException(io.trino.spi.security.AccessDeniedException) NONCE(io.trino.server.security.oauth2.OAuth2Service.NONCE) GET(javax.ws.rs.GET) OkHttpUtil.setupSsl(io.trino.client.OkHttpUtil.setupSsl) MINUTES(java.util.concurrent.TimeUnit.MINUTES) LOCATION(javax.ws.rs.core.HttpHeaders.LOCATION) HttpServletRequest(javax.servlet.http.HttpServletRequest) Identity(io.trino.spi.security.Identity) Response(okhttp3.Response) SC_UNAUTHORIZED(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED) Resources(com.google.common.io.Resources) Files(java.nio.file.Files) IOException(java.io.IOException) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) File(java.io.File) WWW_AUTHENTICATE(javax.ws.rs.core.HttpHeaders.WWW_AUTHENTICATE) OkHttpClient(okhttp3.OkHttpClient) ChronoUnit(java.time.temporal.ChronoUnit) Paths(java.nio.file.Paths) OAUTH2_COOKIE(io.trino.server.ui.OAuthWebUiCookie.OAUTH2_COOKIE) AllowAllSystemAccessControl(io.trino.plugin.base.security.AllowAllSystemAccessControl) Module(com.google.inject.Module) AUTHENTICATED_USER(io.trino.server.security.ResourceSecurity.AccessType.AUTHENTICATED_USER) Date(java.util.Date) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Key(com.google.inject.Key) AUTHORIZATION(com.google.common.net.HttpHeaders.AUTHORIZATION) SC_SEE_OTHER(javax.servlet.http.HttpServletResponse.SC_SEE_OTHER) URI(java.net.URI) WEB_UI(io.trino.server.security.ResourceSecurity.AccessType.WEB_UI) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer) OptionalBinder.newOptionalBinder(com.google.inject.multibindings.OptionalBinder.newOptionalBinder) ImmutableSet(com.google.common.collect.ImmutableSet) Context(javax.ws.rs.core.Context) ImmutableMap(com.google.common.collect.ImmutableMap) BeforeClass(org.testng.annotations.BeforeClass) Assert.assertNotNull(org.testng.Assert.assertNotNull) Credentials(okhttp3.Credentials) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) Base64(java.util.Base64) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Principal(java.security.Principal) CookieManager(java.net.CookieManager) SC_OK(javax.servlet.http.HttpServletResponse.SC_OK) HttpUriBuilder.uriBuilderFrom(io.airlift.http.client.HttpUriBuilder.uriBuilderFrom) JaxrsBinder.jaxrsBinder(io.airlift.jaxrs.JaxrsBinder.jaxrsBinder) MetadataManager.createTestMetadataManager(io.trino.metadata.MetadataManager.createTestMetadataManager) Optional(java.util.Optional) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) Pattern(java.util.regex.Pattern) HttpUrl(okhttp3.HttpUrl) Instant.now(java.time.Instant.now) DataProvider(org.testng.annotations.DataProvider) JwtUtil.newJwtBuilder(io.trino.server.security.jwt.JwtUtil.newJwtBuilder) OAuth2Client(io.trino.server.security.oauth2.OAuth2Client) Headers(okhttp3.Headers) AtomicReference(java.util.concurrent.atomic.AtomicReference) Inject(javax.inject.Inject) Cookie(okhttp3.Cookie) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) HttpRequestSessionContextFactory(io.trino.server.HttpRequestSessionContextFactory) UI_LOCATION(io.trino.server.ui.FormWebUiAuthenticationFilter.UI_LOCATION) TestingHttpServer(io.airlift.http.server.testing.TestingHttpServer) Keys.hmacShaKeyFor(io.jsonwebtoken.security.Keys.hmacShaKeyFor) AccessDeniedException.denyImpersonateUser(io.trino.spi.security.AccessDeniedException.denyImpersonateUser) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) SC_FORBIDDEN(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN) Assert.assertTrue(org.testng.Assert.assertTrue) TRINO_HEADERS(io.trino.client.ProtocolHeaders.TRINO_HEADERS) OkHttpClient(okhttp3.OkHttpClient) TestingHttpServer(io.airlift.http.server.testing.TestingHttpServer) HttpServerInfo(io.airlift.http.server.HttpServerInfo) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer) Test(org.testng.annotations.Test)

Example 64 with Route

use of okhttp3.Route in project trino by trinodb.

the class TestWebUi method testJwtAuthenticator.

@Test
public void testJwtAuthenticator() throws Exception {
    try (TestingTrinoServer server = TestingTrinoServer.builder().setProperties(ImmutableMap.<String, String>builder().putAll(SECURE_PROPERTIES).put("http-server.authentication.type", "jwt").put("http-server.authentication.jwt.key-file", HMAC_KEY).buildOrThrow()).build()) {
        HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
        String nodeId = server.getInstance(Key.get(NodeInfo.class)).getNodeId();
        testLogIn(httpServerInfo.getHttpUri(), FORM_LOGIN_USER, TEST_PASSWORD, false);
        testNeverAuthorized(httpServerInfo.getHttpsUri(), client);
        SecretKey hmac = hmacShaKeyFor(Base64.getDecoder().decode(Files.readString(Paths.get(HMAC_KEY)).trim()));
        String token = newJwtBuilder().signWith(hmac).setSubject("test-user").setExpiration(Date.from(ZonedDateTime.now().plusMinutes(5).toInstant())).compact();
        OkHttpClient clientWithJwt = client.newBuilder().authenticator((route, response) -> response.request().newBuilder().header(AUTHORIZATION, "Bearer " + token).build()).build();
        testAlwaysAuthorized(httpServerInfo.getHttpsUri(), clientWithJwt, nodeId);
    }
}
Also used : ResourceSecurity(io.trino.server.security.ResourceSecurity) X_FORWARDED_PORT(com.google.common.net.HttpHeaders.X_FORWARDED_PORT) Date(java.util.Date) ZonedDateTime(java.time.ZonedDateTime) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Key(com.google.inject.Key) NodeInfo(io.airlift.node.NodeInfo) AUTHORIZATION(com.google.common.net.HttpHeaders.AUTHORIZATION) Test(org.testng.annotations.Test) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter) HttpServerConfig(io.airlift.http.server.HttpServerConfig) ContainerRequestContext(javax.ws.rs.container.ContainerRequestContext) JwsHeader(io.jsonwebtoken.JwsHeader) HttpCookie(java.net.HttpCookie) SC_SEE_OTHER(javax.servlet.http.HttpServletResponse.SC_SEE_OTHER) FormBody(okhttp3.FormBody) JwtBuilder(io.jsonwebtoken.JwtBuilder) DISABLED_LOCATION(io.trino.server.ui.FormWebUiAuthenticationFilter.DISABLED_LOCATION) URI(java.net.URI) WEB_UI(io.trino.server.security.ResourceSecurity.AccessType.WEB_UI) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer) Path(java.nio.file.Path) X_FORWARDED_PROTO(com.google.common.net.HttpHeaders.X_FORWARDED_PROTO) OptionalBinder.newOptionalBinder(com.google.inject.multibindings.OptionalBinder.newOptionalBinder) Assert.assertEquals(io.trino.testing.assertions.Assert.assertEquals) PemReader(io.airlift.security.pem.PemReader) Request(okhttp3.Request) UNAUTHORIZED(javax.ws.rs.core.Response.Status.UNAUTHORIZED) ImmutableSet(com.google.common.collect.ImmutableSet) Context(javax.ws.rs.core.Context) HttpServlet(javax.servlet.http.HttpServlet) ImmutableMap(com.google.common.collect.ImmutableMap) JavaNetCookieJar(okhttp3.JavaNetCookieJar) BeforeClass(org.testng.annotations.BeforeClass) AUTHENTICATED_IDENTITY(io.trino.server.HttpRequestSessionContextFactory.AUTHENTICATED_IDENTITY) PreparedStatementEncoder(io.trino.server.protocol.PreparedStatementEncoder) GuardedBy(javax.annotation.concurrent.GuardedBy) BasicPrincipal(io.trino.spi.security.BasicPrincipal) Preconditions.checkState(com.google.common.base.Preconditions.checkState) UncheckedIOException(java.io.UncheckedIOException) SC_NOT_FOUND(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND) Base64(java.util.Base64) HttpServerInfo(io.airlift.http.server.HttpServerInfo) HttpHeaders(javax.ws.rs.core.HttpHeaders) Principal(java.security.Principal) AccessControl(io.trino.security.AccessControl) PrivateKey(java.security.PrivateKey) CookieManager(java.net.CookieManager) SC_OK(javax.servlet.http.HttpServletResponse.SC_OK) HttpUriBuilder.uriBuilderFrom(io.airlift.http.client.HttpUriBuilder.uriBuilderFrom) JaxrsBinder.jaxrsBinder(io.airlift.jaxrs.JaxrsBinder.jaxrsBinder) MetadataManager.createTestMetadataManager(io.trino.metadata.MetadataManager.createTestMetadataManager) Optional(java.util.Optional) SecretKey(javax.crypto.SecretKey) Predicate.not(java.util.function.Predicate.not) ProtocolConfig(io.trino.server.ProtocolConfig) AccessDeniedException(io.trino.spi.security.AccessDeniedException) NONCE(io.trino.server.security.oauth2.OAuth2Service.NONCE) UI_LOGIN(io.trino.server.ui.FormWebUiAuthenticationFilter.UI_LOGIN) GET(javax.ws.rs.GET) JwtUtil.newJwtBuilder(io.trino.server.security.jwt.JwtUtil.newJwtBuilder) OAuth2Client(io.trino.server.security.oauth2.OAuth2Client) CALLBACK_ENDPOINT(io.trino.server.security.oauth2.OAuth2CallbackResource.CALLBACK_ENDPOINT) Hashing(com.google.common.hash.Hashing) OkHttpUtil.setupSsl(io.trino.client.OkHttpUtil.setupSsl) MINUTES(java.util.concurrent.TimeUnit.MINUTES) RequestBody(okhttp3.RequestBody) Inject(javax.inject.Inject) UI_LOGOUT(io.trino.server.ui.FormWebUiAuthenticationFilter.UI_LOGOUT) HttpServletRequest(javax.servlet.http.HttpServletRequest) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Identity(io.trino.spi.security.Identity) Objects.requireNonNull(java.util.Objects.requireNonNull) Response(okhttp3.Response) HttpRequestSessionContextFactory(io.trino.server.HttpRequestSessionContextFactory) SC_UNAUTHORIZED(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED) TestingHttpServer(io.airlift.http.server.testing.TestingHttpServer) X_FORWARDED_HOST(com.google.common.net.HttpHeaders.X_FORWARDED_HOST) Keys.hmacShaKeyFor(io.jsonwebtoken.security.Keys.hmacShaKeyFor) LOGIN_FORM(io.trino.server.ui.FormWebUiAuthenticationFilter.LOGIN_FORM) Resources(com.google.common.io.Resources) Files(java.nio.file.Files) UTF_8(java.nio.charset.StandardCharsets.UTF_8) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Iterables.getOnlyElement(com.google.common.collect.Iterables.getOnlyElement) File(java.io.File) PasswordAuthenticatorManager(io.trino.server.security.PasswordAuthenticatorManager) OkHttpClient(okhttp3.OkHttpClient) LOCATION(com.google.common.net.HttpHeaders.LOCATION) Paths(java.nio.file.Paths) Assert.assertTrue(org.testng.Assert.assertTrue) SecretKey(javax.crypto.SecretKey) OkHttpClient(okhttp3.OkHttpClient) HttpServerInfo(io.airlift.http.server.HttpServerInfo) TestingTrinoServer(io.trino.server.testing.TestingTrinoServer) Test(org.testng.annotations.Test)

Example 65 with Route

use of okhttp3.Route in project hop by rabbitmq.

the class OkHttpRestTemplateConfigurator method getRequestFactory.

private ClientHttpRequestFactory getRequestFactory(final URL url, final String username, final String password, final SSLSocketFactory sslSocketFactory, final X509TrustManager trustManager, final OkHttpClientBuilderConfigurator configurator) {
    Assert.notNull(configurator, "configurator is required; it must not be null");
    String theUser = username;
    String thePassword = password;
    String userInfo = url.getUserInfo();
    if (userInfo != null && theUser == null) {
        String[] userParts = userInfo.split(":");
        if (userParts.length > 0) {
            theUser = Utils.decode(userParts[0]);
        }
        if (userParts.length > 1) {
            thePassword = Utils.decode(userParts[1]);
        }
    }
    final String credentials = Credentials.basic(theUser, thePassword);
    // configure OkHttpClient.Builder essentials
    final OkHttpClient.Builder bldr = new OkHttpClient.Builder().authenticator((route, response) -> response.request().newBuilder().header("Authorization", credentials).build());
    if (sslSocketFactory != null && trustManager != null) {
        bldr.sslSocketFactory(sslSocketFactory, trustManager);
    }
    // this lets the user perform non-essential configuration (e.g. timeouts)
    // but reduces the risk of essentials not being set. MK.
    OkHttpClient.Builder b = configurator.configure(bldr);
    OkHttpClient httpClient = b.build();
    return new OkHttp3ClientHttpRequestFactory(httpClient);
}
Also used : OkHttp3ClientHttpRequestFactory(org.springframework.http.client.OkHttp3ClientHttpRequestFactory) OkHttpClient(okhttp3.OkHttpClient)

Aggregations

Response (okhttp3.Response)52 Request (okhttp3.Request)41 IOException (java.io.IOException)40 OkHttpClient (okhttp3.OkHttpClient)33 Route (okhttp3.Route)31 Proxy (java.net.Proxy)23 InetSocketAddress (java.net.InetSocketAddress)21 Authenticator (okhttp3.Authenticator)18 Test (org.junit.Test)17 Map (java.util.Map)16 List (java.util.List)13 HttpUrl (okhttp3.HttpUrl)13 RequestBody (okhttp3.RequestBody)13 Test (org.junit.jupiter.api.Test)13 Credentials (okhttp3.Credentials)11 ArrayList (java.util.ArrayList)10 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)10 File (java.io.File)9 URI (java.net.URI)9 URL (java.net.URL)9