Search in sources :

Example 1 with CredentialFlowState

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");
}
Also used : AcquisitionResponse(io.syndesis.server.credential.AcquisitionResponse) CredentialFlowState(io.syndesis.server.credential.CredentialFlowState) ClientSideState(io.syndesis.server.endpoint.v1.state.ClientSideState) State(io.syndesis.server.credential.AcquisitionResponse.State) OAuth2CredentialFlowState(io.syndesis.server.credential.OAuth2CredentialFlowState) CredentialFlowState(io.syndesis.server.credential.CredentialFlowState) OAuth2CredentialFlowState(io.syndesis.server.credential.OAuth2CredentialFlowState) OAuth2CredentialFlowState(io.syndesis.server.credential.OAuth2CredentialFlowState) URI(java.net.URI) Test(org.junit.Test)

Example 2 with CredentialFlowState

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);
}
Also used : ConfigurationProperty(io.syndesis.common.model.connection.ConfigurationProperty) Cookie(javax.servlet.http.Cookie) CredentialFlowState(io.syndesis.server.credential.CredentialFlowState) Connection(io.syndesis.common.model.connection.Connection) Date(java.util.Date)

Example 3 with CredentialFlowState

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();
}
Also used : AcquisitionResponse(io.syndesis.server.credential.AcquisitionResponse) AcquisitionFlow(io.syndesis.server.credential.AcquisitionFlow) CredentialFlowState(io.syndesis.server.credential.CredentialFlowState) NewCookie(javax.ws.rs.core.NewCookie) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 4 with CredentialFlowState

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();
}
Also used : CredentialFlowState(io.syndesis.server.credential.CredentialFlowState) URI(java.net.URI) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 5 with CredentialFlowState

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;
    });
}
Also used : Arrays(java.util.Arrays) CredentialFlowState(io.syndesis.server.credential.CredentialFlowState) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HttpMethod(org.springframework.http.HttpMethod) Autowired(org.springframework.beans.factory.annotation.Autowired) Test(org.junit.Test) OAuthToken(org.springframework.social.oauth1.OAuthToken) Assertions.entry(org.assertj.core.api.Assertions.entry) Awaitility.given(org.awaitility.Awaitility.given) OAuth1CredentialFlowState(io.syndesis.server.credential.OAuth1CredentialFlowState) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) Connection(io.syndesis.common.model.connection.Connection) CredentialProvider(io.syndesis.server.credential.CredentialProvider) CredentialProviderLocator(io.syndesis.server.credential.CredentialProviderLocator) ResponseEntity(org.springframework.http.ResponseEntity) OAuth1CredentialProvider(io.syndesis.server.credential.OAuth1CredentialProvider) OAuthAppHandler(io.syndesis.server.endpoint.v1.handler.setup.OAuthAppHandler) SECONDS(java.util.concurrent.TimeUnit.SECONDS) CredentialFlowState(io.syndesis.server.credential.CredentialFlowState) OAuth1CredentialFlowState(io.syndesis.server.credential.OAuth1CredentialFlowState) Connection(io.syndesis.common.model.connection.Connection) OAuth1CredentialFlowState(io.syndesis.server.credential.OAuth1CredentialFlowState) OAuthAppHandler(io.syndesis.server.endpoint.v1.handler.setup.OAuthAppHandler) OAuthToken(org.springframework.social.oauth1.OAuthToken) CredentialProvider(io.syndesis.server.credential.CredentialProvider) OAuth1CredentialProvider(io.syndesis.server.credential.OAuth1CredentialProvider) Test(org.junit.Test)

Aggregations

CredentialFlowState (io.syndesis.server.credential.CredentialFlowState)5 Connection (io.syndesis.common.model.connection.Connection)2 AcquisitionResponse (io.syndesis.server.credential.AcquisitionResponse)2 URI (java.net.URI)2 Test (org.junit.Test)2 ConfigurationProperty (io.syndesis.common.model.connection.ConfigurationProperty)1 AcquisitionFlow (io.syndesis.server.credential.AcquisitionFlow)1 State (io.syndesis.server.credential.AcquisitionResponse.State)1 CredentialProvider (io.syndesis.server.credential.CredentialProvider)1 CredentialProviderLocator (io.syndesis.server.credential.CredentialProviderLocator)1 OAuth1CredentialFlowState (io.syndesis.server.credential.OAuth1CredentialFlowState)1 OAuth1CredentialProvider (io.syndesis.server.credential.OAuth1CredentialProvider)1 OAuth2CredentialFlowState (io.syndesis.server.credential.OAuth2CredentialFlowState)1 OAuthAppHandler (io.syndesis.server.endpoint.v1.handler.setup.OAuthAppHandler)1 ClientSideState (io.syndesis.server.endpoint.v1.state.ClientSideState)1 Arrays (java.util.Arrays)1 Date (java.util.Date)1 List (java.util.List)1 SECONDS (java.util.concurrent.TimeUnit.SECONDS)1 Cookie (javax.servlet.http.Cookie)1