use of io.syndesis.server.credential.CredentialFlowState in project syndesis by syndesisio.
the class CredentialITCase method shouldInitiateCredentialFlow.
@Test
public void shouldInitiateCredentialFlow() throws UnsupportedEncodingException {
final ResponseEntity<AcquisitionResponse> acquisitionResponse = post("/api/v1/connectors/test-provider/credentials", Collections.singletonMap("returnUrl", "/ui#state"), AcquisitionResponse.class, tokenRule.validToken(), HttpStatus.ACCEPTED);
assertThat(acquisitionResponse.hasBody()).as("Should present a acquisition response in the HTTP body").isTrue();
final AcquisitionResponse response = acquisitionResponse.getBody();
assertThat(response.getType()).isEqualTo(Type.OAUTH2);
final String redirectUrl = response.getRedirectUrl();
assertThat(redirectUrl).as("Should redirect to Salesforce and containthe correct callback URL").startsWith("https://test/oauth2/authorize?client_id=testClientId&response_type=code&redirect_uri=").contains(encode("/api/v1/credentials/callback", "ASCII"));
final MultiValueMap<String, String> params = UriComponentsBuilder.fromHttpUrl(redirectUrl).build().getQueryParams();
final String state = params.getFirst("state");
assertThat(state).as("state parameter should be set").isNotEmpty();
final State responseStateInstruction = response.state();
assertThat(responseStateInstruction).as("acquisition response should contain the state instruction").isNotNull();
assertThat(responseStateInstruction.persist()).isEqualByComparingTo(State.Persist.COOKIE);
assertThat(responseStateInstruction.spec()).isNotEmpty();
final CredentialFlowState credentialFlowState = clientSideState.restoreFrom(Cookie.valueOf(responseStateInstruction.spec()), CredentialFlowState.class);
final CredentialFlowState expected = new OAuth2CredentialFlowState.Builder().key("test-state").providerId("test-provider").build();
assertThat(credentialFlowState).as("The flow state should be as expected").isEqualToIgnoringGivenFields(expected, "returnUrl");
final URI returnUrl = credentialFlowState.getReturnUrl();
assertThat(returnUrl).isNotNull();
assertThat(returnUrl.isAbsolute()).isTrue();
assertThat(returnUrl.getPath()).isEqualTo("/ui");
assertThat(returnUrl.getFragment()).isEqualTo("state");
}
use of io.syndesis.server.credential.CredentialFlowState in project syndesis by syndesisio.
the class ConnectionHandler method create.
@Override
public Connection create(@Context SecurityContext sec, @ConvertGroup(from = Default.class, to = AllValidations.class) final Connection connection) {
final Date rightNow = new Date();
// Lets make sure we store encrypt secrets.
Map<String, String> configuredProperties = connection.getConfiguredProperties();
Map<String, ConfigurationProperty> connectorProperties = getConnectorProperties(connection.getConnectorId());
configuredProperties = encryptionComponent.encryptPropertyValues(configuredProperties, connectorProperties);
final Connection updatedConnection = new Connection.Builder().createFrom(connection).createdDate(rightNow).lastUpdated(rightNow).configuredProperties(configuredProperties).userId(sec.getUserPrincipal().getName()).build();
final Set<CredentialFlowState> flowStates = CredentialFlowState.Builder.restoreFrom(state::restoreFrom, request);
final Connection connectionToCreate = flowStates.stream().map(s -> {
final Cookie removal = new Cookie(s.persistenceKey(), "");
removal.setPath("/");
removal.setMaxAge(0);
response.addCookie(removal);
return credentials.apply(updatedConnection, s);
}).findFirst().orElse(updatedConnection);
return Creator.super.create(sec, connectionToCreate);
}
use of io.syndesis.server.credential.CredentialFlowState in project syndesis by syndesisio.
the class ConnectorCredentialHandler method create.
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response create(@NotNull @Valid final AcquisitionRequest request, @Context final HttpServletRequest httpRequest) {
final AcquisitionFlow acquisitionFlow = credentials.acquire(connectorId, apiBase(httpRequest), absoluteTo(httpRequest, request.getReturnUrl()));
final CredentialFlowState flowState = acquisitionFlow.state().get();
final NewCookie cookie = state.persist(flowState.persistenceKey(), "/", flowState);
final AcquisitionResponse acquisitionResponse = AcquisitionResponse.Builder.from(acquisitionFlow).state(State.Builder.cookie(cookie.toString())).build();
return Response.accepted().entity(acquisitionResponse).build();
}
use of io.syndesis.server.credential.CredentialFlowState in project syndesis by syndesisio.
the class CredentialHandler method callback.
@GET
@Path("/callback")
public Response callback(@Context final HttpServletRequest request, @Context final HttpServletResponse response) {
// user could have tried multiple times in parallel or encoutered an
// error, and that leads to multiple `cred-` cookies being present
final Set<CredentialFlowState> allStatesFromRequest;
try {
allStatesFromRequest = CredentialFlowState.Builder.restoreFrom(state::restoreFrom, request);
} catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") final RuntimeException e) {
LOG.debug("Unable to restore credential flow state from request", e);
return fail(request, response, "Unable to restore the state of authorization");
}
if (allStatesFromRequest.isEmpty()) {
return fail(request, response, "Unable to recall the state of authorization, called callback without initiating OAuth autorization?");
}
// as a fallback pick the newest one
final CredentialFlowState newestState = allStatesFromRequest.iterator().next();
final String providerId = newestState.getProviderId();
final URI returnUrl = newestState.getReturnUrl();
final Optional<CredentialFlowState> maybeUpdatedFlowState;
try {
final Stream<CredentialFlowState> updatedStatesFromRequest = allStatesFromRequest.stream().map(s -> s.updateFrom(request));
// let's try to finish with any remaining flow states, as there
// might be
// many try with each one
maybeUpdatedFlowState = updatedStatesFromRequest.flatMap(s -> tryToFinishAcquisition(request, s)).findFirst();
} catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") final RuntimeException e) {
LOG.debug("Unable to update credential flow state from request", e);
return fail(request, response, returnUrl, providerId, "Unable to update the state of authorization");
}
if (!maybeUpdatedFlowState.isPresent()) {
return fail(request, response, returnUrl, providerId, "Unable to finish authorization, OAuth authorization timed out?");
}
final CredentialFlowState flowState = maybeUpdatedFlowState.get();
final URI successfullReturnUrl = addFragmentTo(flowState.getReturnUrl(), success(flowState.getConnectorId(), "Successfully authorized Syndesis's access"));
return Response.temporaryRedirect(successfullReturnUrl).cookie(state.persist(flowState.persistenceKey(), "/", flowState)).build();
}
use of io.syndesis.server.credential.CredentialFlowState in project syndesis by syndesisio.
the class SetupITCase method updateOauthApp.
@Test
public void updateOauthApp() {
// Validate initial state assumptions.
getOauthApps();
OAuthAppHandler.OAuthApp twitter = new OAuthAppHandler.OAuthApp();
twitter.clientId = "test-id";
twitter.clientSecret = "test-secret";
http(HttpMethod.PUT, "/api/v1/setup/oauth-apps/twitter", twitter, null, tokenRule.validToken(), HttpStatus.NO_CONTENT);
ResponseEntity<OAuthAppHandler.OAuthApp[]> result = get("/api/v1/setup/oauth-apps", OAuthAppHandler.OAuthApp[].class);
List<OAuthAppHandler.OAuthApp> apps = Arrays.asList(result.getBody());
assertThat(apps.size()).isEqualTo(2);
twitter = apps.stream().filter(x -> "twitter".equals(x.id)).findFirst().get();
assertThat(twitter.id).isEqualTo("twitter");
assertThat(twitter.name).isEqualTo("Twitter");
assertThat(twitter.icon).isEqualTo("fa-twitter");
assertThat(twitter.clientId).isEqualTo("test-id");
assertThat(twitter.clientSecret).isEqualTo("test-secret");
// Now that we have configured the app, we should be able to create the
// connection factory.
// The connection factory is setup async so we might need to wait a little bit
// for it to register.
given().ignoreExceptions().await().atMost(10, SECONDS).pollInterval(1, SECONDS).until(() -> {
final CredentialProvider twitterCredentialProvider = locator.providerWithId("twitter");
// preparing is something we could not do with a `null` ConnectionFactory
assertThat(twitterCredentialProvider).isNotNull().isInstanceOfSatisfying(OAuth1CredentialProvider.class, p -> {
final Connection connection = new Connection.Builder().build();
final CredentialFlowState flowState = new OAuth1CredentialFlowState.Builder().accessToken(new OAuthToken("value", "secret")).connectorId("connectorId").build();
final Connection appliedTo = p.applyTo(connection, flowState);
// test that the updated values are used
assertThat(appliedTo.getConfiguredProperties()).contains(entry("consumerKey", "test-id"), entry("consumerSecret", "test-secret"));
});
return true;
});
}
Aggregations