public static SphereAuthConfigBuilder ofAuthConfig(final SphereAuthConfig template) { return ofKeyIdSecret(template.getProjectKey(), template.getClientId(), template.getClientSecret()) .authUrl(template.getAuthUrl()) .scopeStrings(template.getScopes()); }
static SphereAuthConfig of(final String projectKey, final String clientId, final String clientSecret) { return of(projectKey, clientId, clientSecret, AUTH_URL); }
public InvalidClientCredentialsException(final SphereAuthConfig config) { super("Invalid credentials for " + config.getProjectKey() + " on " + config.getAuthUrl()); } }
/** Parses Tokens from a response from the backend authorization service. * @param response Response from the authorization service. */ private Tokens parseResponse(final HttpResponse response) { if (response.getStatusCode() == 401 && response.getResponseBody().isPresent()) { UnauthorizedException authorizationException = new UnauthorizedException(response.toString()); try { final JsonNode jsonNode = JsonUtils.readTree(response.getResponseBody().get()); if (jsonNode.get("error").asText().equals("invalid_client")) { authorizationException = new InvalidClientCredentialsException(config); } } catch (final JsonException e) { authorizationException = new UnauthorizedException(response.toString(), e); } authorizationException.setProjectKey(config.getProjectKey()); authorizationException.setUnderlyingHttpResponse(response); throw authorizationException; } return JsonUtils.readObject(Tokens.typeReference(), response.getResponseBody().get()); } }
public static SphereAuthConfig toSphereAuthConfig(final SphereAuthConfig sphereAuthConfig, final ApiClient apiClient) { final List<SphereScope> scopes = Arrays.stream(apiClient.getScope() .split("\\s")).map(s -> s.split(":")) .map(strings -> strings[0]) .map(SphereProjectScope::of) .collect(Collectors.toList()); return SphereAuthConfigBuilder.ofKeyIdSecret(apiClient.getProjectKey(),apiClient.getId(),apiClient.getSecret()) .scopes(scopes) .authUrl(sphereAuthConfig.getAuthUrl()) .build(); } public static SphereClientConfig toSphereClientConfig(final SphereClientConfig sphereClientConfig, final ApiClient apiClient) {
@Test public void scopes() { final SphereAuthConfig config = SphereAuthConfigBuilder .ofKeyIdSecret("projectKey", "clientId", "clientSecret") .scopes(asList(SphereProjectScope.MANAGE_CUSTOMERS, SphereProjectScope.VIEW_ORDERS)) .build(); assertThat(config.getScopes()).containsExactly("manage_customers", "view_orders"); }
public InvalidClientCredentialsException(final SphereAuthConfig config) { super("Invalid credentials for " + config.getProjectKey() + " on " + config.getAuthUrl(),401); } }
@Test public void shouldSendCorrelationId() throws Exception { final CompletableFuture<HttpResponse> successful = CompletableFutureUtils .successful(HttpResponse.of(200, "{\"access_token\": \"access_token\"}")); when(httpClient.execute(requestCaptor.capture())).thenReturn(successful); tokensSupplier.get().toCompletableFuture().get(); final HttpRequest httpRequest = requestCaptor.getValue(); final Optional<String> correlationIdHeader = httpRequest.getHeaders().findFlatHeader(HttpHeaders.X_CORRELATION_ID); assertThat(correlationIdHeader).isPresent(); final String correlationId = correlationIdHeader.get(); final String[] correlationIdParts = correlationId.split("/"); assertThat(correlationIdParts).hasSize(2); assertThat(correlationIdParts[0]).isEqualTo(authConfig.getProjectKey()); } }
private void scopedTokenBody() { withApiClient(client(), asList(SphereProjectScope.VIEW_CUSTOMERS,SphereProjectScope.VIEW_ORDERS), apiClient -> { final SphereAuthConfig config = toSphereAuthConfig(getSphereClientConfig(),apiClient); assertThat(config.getScopes()).containsExactly("view_customers", "view_orders"); final CompletionStage<String> stringCompletionStage = TokensFacade.fetchAccessToken(config); final String accessToken = blockingWait(stringCompletionStage, 2, SECONDS); assertThat(accessToken).isNotEmpty(); try (final SphereClient client = SphereClientFactory.of() .createClient(getSphereClientConfig(), SphereAccessTokenSupplier.ofConstantToken(accessToken))) { final PagedQueryResult<Customer> customerPagedQueryResult = blockingWait(client.execute(CustomerQuery.of().withLimit(1)), 2, SECONDS); assertThat(customerPagedQueryResult).isNotNull(); } }); }
private HttpRequest newRequest() { final String usernamePassword = format("%s:%s", config.getClientId(), config.getClientSecret()); final String encodedString = Base64.getEncoder().encodeToString(usernamePassword.getBytes(StandardCharsets.UTF_8)); final HttpHeaders httpHeaders = HttpHeaders .of(HttpHeaders.AUTHORIZATION, "Basic " + encodedString) .plus(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); final FormUrlEncodedHttpRequestBody body = FormUrlEncodedHttpRequestBody.of(MapUtils.mapOf("grant_type", "client_credentials", "scope", format("manage_project:%s", config.getProjectKey()))); return HttpRequest.of(POST, config.getAuthUrl() + "/oauth/token", httpHeaders, Optional.of(body)); }
static SphereAuthConfig of(final String projectKey, final String clientId, final String clientSecret) { return of(projectKey, clientId, clientSecret, AUTH_URL); }
exception.setProjectKey(config.getProjectKey()); exception.setUnderlyingHttpResponse(httpResponse); exception.setHttpRequest(httpRequest);
private HttpRequest newRequest() { final String usernamePassword = format("%s:%s", config.getClientId(), config.getClientSecret()); final String encodedString = Base64.getEncoder().encodeToString(usernamePassword.getBytes(StandardCharsets.UTF_8)); final HttpHeaders httpHeaders = HttpHeaders .of(HttpHeaders.AUTHORIZATION, "Basic " + encodedString) .plus(HttpHeaders.USER_AGENT, BuildInfo.userAgent()) .plus(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); final FormUrlEncodedHttpRequestBody body = FormUrlEncodedHttpRequestBody.of(MapUtils.mapOf("grant_type", "client_credentials", "scope", format("manage_project:%s", config.getProjectKey()))); return HttpRequest.of(POST, config.getAuthUrl() + "/oauth/token", httpHeaders, body); }
@Test public void validateClientSecret() throws Exception { assertThatThrownBy(() -> SphereAuthConfig.of("here", "here", null, "here")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("clientSecret"); assertThatThrownBy(() -> SphereAuthConfig.of("here", "here", "", "here")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("clientSecret"); }
exception.setProjectKey(config.getProjectKey()); exception.setUnderlyingHttpResponse(httpResponse); exception.setHttpRequest(httpRequest);
private HttpRequest newRequest() { final String usernamePassword = format("%s:%s", config.getClientId(), config.getClientSecret()); final String encodedString = Base64.getEncoder().encodeToString(usernamePassword.getBytes(StandardCharsets.UTF_8)); final String correlationId = String.join("/", config.getProjectKey(), UUID.randomUUID().toString()); final HttpHeaders httpHeaders = HttpHeaders .of(HttpHeaders.AUTHORIZATION, "Basic " + encodedString) .plus(HttpHeaders.USER_AGENT, UserAgentUtils.obtainUserAgent(httpClient)) .plus(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded") .plus(HttpHeaders.X_CORRELATION_ID, correlationId); final String projectKey = config.getProjectKey(); final Map<String, String> data = new HashMap<>(); data.put("grant_type", isPasswordFlow() ? "password" : "client_credentials"); final String scopeValue = config.getScopes().stream() .map(scope -> format("%s:%s", scope, projectKey)) .collect(joining(" ")); data.put("scope", scopeValue); if (isPasswordFlow()) { data.put("username", username); data.put("password", password); } final FormUrlEncodedHttpRequestBody body = FormUrlEncodedHttpRequestBody.ofStringMap(data); final String url = isPasswordFlow() ? config.getAuthUrl() + "/oauth/" + projectKey + "/customers/token" : config.getAuthUrl() + "/oauth/token"; final HttpRequest httpRequest = HttpRequest.of(POST, url, httpHeaders, body); return httpRequest; }
@Test public void validateProjectKey() throws Exception { assertThatThrownBy(() -> SphereAuthConfig.of(null, "here", "here", "here")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(""); assertThatThrownBy(() -> SphereAuthConfig.of("", "here", "here", "here")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(""); }
exception.setProjectKey(config.getProjectKey()); exception.setUnderlyingHttpResponse(httpResponse); exception.setHttpRequest(httpRequest);
private HttpRequest newRequest() { final String usernamePassword = format("%s:%s", config.getClientId(), config.getClientSecret()); final String encodedString = Base64.getEncoder().encodeToString(usernamePassword.getBytes(StandardCharsets.UTF_8)); final String correlationId = String.join("/", config.getProjectKey(), UUID.randomUUID().toString()); final HttpHeaders httpHeaders = HttpHeaders .of(HttpHeaders.AUTHORIZATION, "Basic " + encodedString) .plus(HttpHeaders.USER_AGENT, UserAgentUtils.obtainUserAgent(httpClient)) .plus(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded") .plus(HttpHeaders.X_CORRELATION_ID, correlationId); final String projectKey = config.getProjectKey(); final Map<String, String> data = new HashMap<>(); data.put("grant_type", isPasswordFlow() ? "password" : "client_credentials"); final String scopeValue = config.getScopes().stream() .map(scope -> format("%s:%s", scope, projectKey)) .collect(joining(" ")); data.put("scope", scopeValue); if (isPasswordFlow()) { data.put("username", username); data.put("password", password); } final FormUrlEncodedHttpRequestBody body = FormUrlEncodedHttpRequestBody.ofStringMap(data); final String url = isPasswordFlow() ? config.getAuthUrl() + "/oauth/" + projectKey + "/customers/token" : config.getAuthUrl() + "/oauth/token"; final HttpRequest httpRequest = HttpRequest.of(POST, url, httpHeaders, body); return httpRequest; }
@Test public void validateAuthUrl() throws Exception { assertThatThrownBy(() -> SphereAuthConfig.of("here", "here", "here", null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("authUrl"); assertThatThrownBy(() -> SphereAuthConfig.of("here", "here", "here", "")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("authUrl"); } }