org.springframework.social.oauth2.AccessGrant Java Examples

The following examples show how to use org.springframework.social.oauth2.AccessGrant. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SalesforceApplicatorTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldApplyAdditionalProperties() {
    final SalesforceProperties properties = new SalesforceProperties();
    properties.setAppId("appId");
    properties.setAppSecret("appSecret");

    final AccessGrant accessGrant = new AccessGrant("accessToken", "scope", "refreshToken", 1L);

    final SalesforceConnectionFactory salesforce = mock(SalesforceConnectionFactory.class);
    @SuppressWarnings("unchecked")
    final org.springframework.social.connect.Connection<Salesforce> salesforceConnection = mock(
        org.springframework.social.connect.Connection.class);

    final Salesforce salesforceApi = mock(Salesforce.class);
    when(salesforceConnection.getApi()).thenReturn(salesforceApi);
    when(salesforceApi.getInstanceUrl()).thenReturn("https://instance.salesforce.com");

    when(salesforce.createConnection(accessGrant)).thenReturn(salesforceConnection);

    final Connection.Builder mutableConnection = new Connection.Builder();
    final SalesforceApplicator applicator = new SalesforceApplicator(salesforce, properties);
    applicator.additionalApplication(mutableConnection, accessGrant);

    assertThat(mutableConnection.build().getConfiguredProperties())
        .containsExactly(entry("instanceUrl", "https://instance.salesforce.com"));
}
 
Example #2
Source File: OAuth2Applicator.java    From syndesis with Apache License 2.0 6 votes vote down vote up
/**
 * Default implementation that applies {@link SocialProperties} and
 * {@link AccessGrant} to {@link Connection.Builder}.
 */
@Override
public final Connection applyTo(final Connection connection, final AccessGrant accessGrant) {
    final Connection.Builder mutableConnection = new Connection.Builder().createFrom(connection).lastUpdated(new Date());

    Applicator.applyProperty(mutableConnection, clientIdProperty, socialProperties.getAppId());
    Applicator.applyProperty(mutableConnection, clientSecretProperty, socialProperties.getAppSecret());
    Applicator.applyProperty(mutableConnection, accessTokenProperty, accessGrant.getAccessToken());
    Applicator.applyProperty(mutableConnection, refreshTokenProperty, accessGrant.getRefreshToken());
    final Long expireTime = accessGrant.getExpireTime();
    Applicator.applyProperty(mutableConnection, accessTokenExpiresAtProperty, expireTime == null ? null : expireTime.toString());

    additionalApplication(mutableConnection, accessGrant);

    return mutableConnection.build();
}
 
Example #3
Source File: AlipayOAuth2Template.java    From cola with MIT License 6 votes vote down vote up
@Override
protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {

	AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", properties.getAppId(), properties.getPrivateKey(), properties.getPrivateKey(), properties.getCharset(), properties.getPublicKey(), properties.getSignType());
	AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
	request.setCode(parameters.getFirst("credential"));
	request.setGrantType("authorization_code");
	try {
		AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
		if (oauthTokenResponse.isSuccess()) {
			return new AccessGrant(oauthTokenResponse.getAccessToken(), null, oauthTokenResponse.getRefreshToken(), Long.valueOf(oauthTokenResponse.getExpiresIn()));
		}else{
			throw new IllegalArgumentException(oauthTokenResponse.getCode() + ":" + oauthTokenResponse.getMsg());
		}
	} catch (AlipayApiException e) {
		//处理异常
		throw new IllegalArgumentException(e.getMessage());
	}

}
 
Example #4
Source File: GithubOAuth2Template.java    From pre with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {

    RestTemplate restTemplate = new RestTemplate();
    // 自己拼接url
    String clientId = parameters.getFirst("client_id");
    String clientSecret = parameters.getFirst("client_secret");
    String code = parameters.getFirst("code");

    String url = String.format("https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", clientId, clientSecret, code);
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    URI uri = builder.build().encode().toUri();
    String responseStr = restTemplate.getForObject(uri, String.class);
    logger.info("获取accessToke的响应:" + responseStr);
    String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(responseStr, "&");
    String accessToken = StringUtils.substringAfterLast(items[0], "=");
    logger.info("获取Toke的响应:" + accessToken);
    return new AccessGrant(accessToken, null, null, null);
}
 
Example #5
Source File: GiteeOAuth2Template.java    From pre with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {

    // https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
    // 自己拼接url
    String clientId = parameters.getFirst("client_id");
    String clientSecret = parameters.getFirst("client_secret");
    String code = parameters.getFirst("code");
    String redirectUri = parameters.getFirst("redirect_uri");

    String url = String.format("https://gitee.com/oauth/token?grant_type=authorization_code&code=%s&client_id=%s&redirect_uri=%s&client_secret=%s", code, clientId, redirectUri, clientSecret);
    String post = HttpUtil.post(url, "",5000);

    log.info("获取accessToke的响应:" + post);
    JSONObject object = JSONObject.parseObject(post);
    String accessToken = (String) object.get("access_token");
    String scope = (String) object.get("scope");
    String refreshToken = (String) object.get("refresh_token");
    int expiresIn = (Integer) object.get("expires_in");

    log.info("获取Toke的响应:{},scope响应:{},refreshToken响应:{},expiresIn响应:{}", accessToken, scope, refreshToken, expiresIn);
    return new AccessGrant(accessToken, scope, refreshToken, (long) expiresIn);
}
 
Example #6
Source File: CredentialITCase.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldApplyOAuthPropertiesToNewlyCreatedConnections() {
    final OAuth2CredentialFlowState flowState = new OAuth2CredentialFlowState.Builder()
        .providerId("test-provider")
        .key("key")
        .accessGrant(new AccessGrant("token"))
        .build();

    final HttpHeaders cookies = persistAsCookie(flowState);

    final Connection newConnection = new Connection.Builder().name("Test connection").connectorId("test-provider").build();
    final ResponseEntity<Connection> connectionResponse = http(HttpMethod.POST, "/api/v1/connections",
        newConnection, Connection.class, tokenRule.validToken(), cookies, HttpStatus.OK);

    assertThat(connectionResponse.hasBody()).as("Should contain created connection").isTrue();

    final Connection createdConnection = connectionResponse.getBody();
    assertThat(createdConnection.isDerived()).isTrue();
    assertThat(createdConnection.getConfiguredProperties()).containsOnly(entry("accessToken", "token"),
        entry("clientId", "appId"), entry("clientSecret", "appSecret"));
}
 
Example #7
Source File: CredentialITCase.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldApplyOAuthPropertiesToConnectionUpdates() {
    final OAuth2CredentialFlowState flowState = new OAuth2CredentialFlowState.Builder()
        .providerId("test-provider")
        .key("key")
        .accessGrant(new AccessGrant("token"))
        .build();

    final HttpHeaders cookies = persistAsCookie(flowState);

    final Connection newConnection = new Connection.Builder()
        .id("test-connection")
        .name("Test connection")
        .connectorId("test-provider")
        .build();

    final ResponseEntity<Void> connectionResponse = http(HttpMethod.PUT, "/api/v1/connections/test-connection",
        newConnection, Void.class, tokenRule.validToken(), cookies, HttpStatus.NO_CONTENT);
    assertThat(connectionResponse.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);

    final Connection updatedConnection = dataManager.fetch(Connection.class, "test-connection");
    assertThat(updatedConnection.isDerived()).isTrue();
    assertThat(updatedConnection.getConfiguredProperties()).containsOnly(entry("accessToken", "token"),
        entry("clientId", "appId"), entry("clientSecret", "appSecret"));
}
 
Example #8
Source File: WeixinConnectionFactory.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
/**
 * 由于微信的openId是和accessToken一起返回的,所以在这里直接根据accessToken设置providerUserId即可,不用像QQ那样通过QQAdapter来获取
 *
 * @param accessGrant the access grant
 *
 * @return the string
 */
@Override
protected String extractProviderUserId(AccessGrant accessGrant) {
	if (accessGrant instanceof WeixinAccessGrant) {
		return ((WeixinAccessGrant) accessGrant).getOpenId();
	}
	return null;
}
 
Example #9
Source File: WeixinOAuth2Template.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
/**
 * Exchange for access access grant.
 *
 * @param authorizationCode the authorization code
 * @param redirectUri       the redirect uri
 * @param parameters        the parameters
 *
 * @return the access grant
 */
@Override
public AccessGrant exchangeForAccess(String authorizationCode, String redirectUri,
                                     MultiValueMap<String, String> parameters) {

	StringBuilder accessTokenRequestUrl = new StringBuilder(accessTokenUrl);

	accessTokenRequestUrl.append("?appid=").append(clientId);
	accessTokenRequestUrl.append("&secret=").append(clientSecret);
	accessTokenRequestUrl.append("&code=").append(authorizationCode);
	accessTokenRequestUrl.append("&grant_type=authorization_code");
	accessTokenRequestUrl.append("&redirect_uri=").append(redirectUri);

	return getAccessToken(accessTokenRequestUrl);
}
 
Example #10
Source File: RestOAuth2Template.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
    JsonNode response = getRestTemplate().postForObject(accessTokenUrl, parameters, JsonNode.class);

    ObjectMapper mapper = new ObjectMapper();
    @SuppressWarnings("unchecked")
    Map<String, Object> result = mapper.convertValue(response, Map.class);
    this.id = (String)result.get("id_token");
    return this.createAccessGrant((String) result.get("access_token"), (String) result.get("scope"),
            (String) result.get("refresh_token"), getIntegerValue(result, "expires_in"), result);
}
 
Example #11
Source File: QQOAuth2Template.java    From FEBS-Security with Apache License 2.0 5 votes vote down vote up
@Override
protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
    // access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14
    String result = this.getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);
    log.info("responseToken: {}", result);
    String[] params = StringUtils.splitByWholeSeparatorPreserveAllTokens(result, "&");

    String accessToken = StringUtils.substringAfterLast(params[0], "=");
    Long expiresIn = Long.valueOf(StringUtils.substringAfterLast(params[1], "="));
    String refreshToken = StringUtils.substringAfterLast(params[2], "=");
    return new AccessGrant(accessToken, null, refreshToken, expiresIn);
}
 
Example #12
Source File: WeiXinOAuth2Template.java    From FEBS-Security with Apache License 2.0 5 votes vote down vote up
@Override
public AccessGrant exchangeForAccess(String authorizationCode, String redirectUri, MultiValueMap<String, String> parameters) {
    StringBuilder accessTokenRequestUrl = new StringBuilder(accessTokenUrl);

    accessTokenRequestUrl.append("?appid=").append(clientId);
    accessTokenRequestUrl.append("&secret=").append(clientSecret);
    accessTokenRequestUrl.append("&code=").append(authorizationCode);
    accessTokenRequestUrl.append("&grant_type=authorization_code");
    accessTokenRequestUrl.append("&redirect_uri=").append(redirectUri);

    return getAccessToken(accessTokenRequestUrl);
}
 
Example #13
Source File: WeiXinOAuth2Template.java    From FEBS-Security with Apache License 2.0 5 votes vote down vote up
@Override
public AccessGrant refreshAccess(String refreshToken, MultiValueMap<String, String> additionalParameters) {

    StringBuilder refreshTokenUrl = new StringBuilder(FebsConstant.WEIXIN_REFRESH_TOKEN_URL);

    refreshTokenUrl.append("?appid=").append(clientId);
    refreshTokenUrl.append("&grant_type=refresh_token");
    refreshTokenUrl.append("&refresh_token=").append(refreshToken);

    return getAccessToken(refreshTokenUrl);
}
 
Example #14
Source File: WeiXinOAuth2Template.java    From FEBS-Security with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private AccessGrant getAccessToken(StringBuilder accessTokenRequestUrl) {

    logger.info("获取access_token, 请求URL{} ", accessTokenRequestUrl.toString());
    String response = getRestTemplate().getForObject(accessTokenRequestUrl.toString(), String.class);
    logger.info("获取access_token, 响应内容{} ", response);

    Map<String, Object> result = null;
    try {
        result = new ObjectMapper().readValue(response, Map.class);
    } catch (Exception e) {
        logger.error("获取微信AccessToken失败", e);
    }

    if (StringUtils.isNotBlank(MapUtils.getString(result, "errcode"))) {
        String errcode = MapUtils.getString(result, "errcode");
        String errmsg = MapUtils.getString(result, "errmsg");
        throw new FebsCredentialExcetion("获取access token失败, errcode:" + errcode + ", errmsg:" + errmsg);
    }

    WeiXinAccessGrant accessToken = new WeiXinAccessGrant(
            MapUtils.getString(result, "access_token"),
            MapUtils.getString(result, "scope"),
            MapUtils.getString(result, "refresh_token"),
            MapUtils.getLong(result, "expires_in"));

    accessToken.setOpenId(MapUtils.getString(result, "openid"));

    return accessToken;
}
 
Example #15
Source File: WeiXinConnectionFactory.java    From FEBS-Security with Apache License 2.0 5 votes vote down vote up
@Override
protected String extractProviderUserId(AccessGrant accessGrant) {
    if (accessGrant instanceof WeiXinAccessGrant) {
        return ((WeiXinAccessGrant) accessGrant).getOpenId();
    }
    return null;
}
 
Example #16
Source File: SpringSocialTokenServices.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2Authentication loadAuthentication(String accessToken)
		throws AuthenticationException, InvalidTokenException {
	AccessGrant accessGrant = new AccessGrant(accessToken);
	Connection<?> connection = this.connectionFactory.createConnection(accessGrant);
	UserProfile user = connection.fetchUserProfile();
	return extractAuthentication(user);
}
 
Example #17
Source File: TestCredentialProviderFactory.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public CredentialProvider create(final SocialProperties properties) {
    @SuppressWarnings("unchecked")
    final OAuth2ConnectionFactory<Object> connectionFactory = mock(OAuth2ConnectionFactory.class);
    when(connectionFactory.generateState()).thenReturn("test-state");

    properties.setAppId("appId");
    properties.setAppSecret("appSecret");

    final OAuth2Applicator applicator = new OAuth2Applicator(properties);
    applicator.setAccessTokenProperty("accessToken");
    applicator.setClientIdProperty("clientId");
    applicator.setClientSecretProperty("clientSecret");
    applicator.setRefreshTokenProperty("refreshToken");

    final CredentialProvider credentialProvider = new OAuth2CredentialProvider<>("test-provider", connectionFactory,
        applicator, Collections.emptyMap());

    final OAuth2Operations operations = spy(new OAuth2Template("testClientId", "testClientSecret",
        "https://test/oauth2/authorize", "https://test/oauth2/token"));
    doReturn(new AccessGrant("token")).when(operations).exchangeForAccess(ArgumentMatchers.anyString(),
        ArgumentMatchers.anyString(), ArgumentMatchers.isNull());

    when(connectionFactory.getOAuthOperations()).thenReturn(operations);

    return credentialProvider;
}
 
Example #18
Source File: CredentialITCase.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReceiveCallbacksFromResourceProviders() {
    final OAuth2CredentialFlowState flowState = new OAuth2CredentialFlowState.Builder().providerId("test-provider")
        .key(UUID.randomUUID().toString()).returnUrl(URI.create("/ui#state")).build();

    final HttpHeaders cookies = persistAsCookie(flowState);

    final ResponseEntity<Void> callbackResponse = http(HttpMethod.GET,
        "/api/v1/credentials/callback?state=test-state&code=code", null, Void.class, null, cookies,
        HttpStatus.TEMPORARY_REDIRECT);

    assertThat(callbackResponse.getStatusCode()).as("Status should be temporarry redirect (307)")
        .isEqualTo(HttpStatus.TEMPORARY_REDIRECT);
    assertThat(callbackResponse.hasBody()).as("Should not contain HTTP body").isFalse();
    assertThat(callbackResponse.getHeaders().getLocation().toString()).matches(
        "http.?://localhost:[0-9]*/api/v1/ui#%7B%22connectorId%22:%22test-provider%22,%22message%22:%22Successfully%20authorized%20Syndesis's%20access%22,%22status%22:%22SUCCESS%22%7D");

    final List<String> receivedCookies = callbackResponse.getHeaders().get("Set-Cookie");
    assertThat(receivedCookies).hasSize(1);

    final OAuth2CredentialFlowState endingFlowState = clientSideState
        .restoreFrom(Cookie.valueOf(receivedCookies.get(0)), OAuth2CredentialFlowState.class);

    // AccessGrant does not implement equals/hashCode
    assertThat(endingFlowState).isEqualToIgnoringGivenFields(
        new OAuth2CredentialFlowState.Builder().createFrom(flowState).code("code").build(), "accessGrant");
    assertThat(endingFlowState.getAccessGrant()).isEqualToComparingFieldByField(new AccessGrant("token"));
}
 
Example #19
Source File: CredentialsTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFinishOAuth2Acquisition() {
    final OAuth2ConnectionFactory<?> oauth2 = mock(OAuth2ConnectionFactory.class);

    final OAuth2Applicator applicator = new OAuth2Applicator(properties);
    applicator.setAccessTokenProperty("accessTokenProperty");
    applicator.setClientIdProperty("clientIdProperty");
    applicator.setClientSecretProperty("clientSecretProperty");
    applicator.setRefreshTokenProperty("refreshTokenProperty");

    when(locator.providerWithId("providerId"))
    .thenReturn(new OAuth2CredentialProvider<>("providerId", oauth2, applicator, Collections.emptyMap()));
    final OAuth2Operations operations = mock(OAuth2Operations.class);
    when(oauth2.getOAuthOperations()).thenReturn(operations);

    final AccessGrant accessGrant = new AccessGrant("accessToken", "scope", "refreshToken", 1L);
    when(operations.exchangeForAccess("code", "https://syndesis.io/api/v1/credentials/callback", null))
    .thenReturn(accessGrant);

    final CredentialFlowState flowState = new OAuth2CredentialFlowState.Builder().providerId("providerId")
        .returnUrl(URI.create("/ui#state")).code("code").state("state").build();

    final CredentialFlowState finalFlowState = credentials.finishAcquisition(flowState,
        URI.create("https://syndesis.io/api/v1/"));

    assertThat(finalFlowState)
    .isEqualTo(new OAuth2CredentialFlowState.Builder().createFrom(flowState).accessGrant(accessGrant).build());
}
 
Example #20
Source File: CredentialsTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAcquireOAuth2CredentialsWithAdditionalQueryParameters() {
    final OAuth2ConnectionFactory<?> oauth2 = mock(OAuth2ConnectionFactory.class);
    @SuppressWarnings("unchecked")
    final Applicator<AccessGrant> applicator = mock(Applicator.class);
    final Map<String, String> queryParameters = new HashMap<>();
    queryParameters.put("q1", "v1");
    queryParameters.put("q2", "v2");
    when(locator.providerWithId("providerId"))
        .thenReturn(new OAuth2CredentialProvider<>("providerId", oauth2, applicator, queryParameters));

    when(oauth2.getScope()).thenReturn("scope");
    when(oauth2.generateState()).thenReturn("state-token");
    final OAuth2Operations operations = mock(OAuth2Operations.class);
    when(oauth2.getOAuthOperations()).thenReturn(operations);
    final ArgumentCaptor<OAuth2Parameters> parameters = ArgumentCaptor.forClass(OAuth2Parameters.class);
    when(operations.buildAuthorizeUrl(parameters.capture())).thenReturn("https://provider.io/oauth/authorize");

    final AcquisitionFlow acquisition = credentials.acquire("providerId", URI.create("https://syndesis.io/api/v1/"),
        URI.create("/ui#state"));

    final CredentialFlowState expectedFlowState = new OAuth2CredentialFlowState.Builder().key("state-token")
        .providerId("providerId").redirectUrl("https://provider.io/oauth/authorize")
        .returnUrl(URI.create("/ui#state")).build();

    final AcquisitionFlow expected = new AcquisitionFlow.Builder().type(Type.OAUTH2)
        .redirectUrl("https://provider.io/oauth/authorize").state(expectedFlowState).build();
    assertThat(acquisition).isEqualTo(expected);

    final OAuth2Parameters capturedParameters = parameters.getValue();
    assertThat(capturedParameters.getRedirectUri()).isEqualTo("https://syndesis.io/api/v1/credentials/callback");
    assertThat(capturedParameters.getScope()).isEqualTo("scope");
    assertThat(capturedParameters.getState()).isEqualTo("state-token");
    assertThat(capturedParameters.get("q1")).containsOnly("v1");
    assertThat(capturedParameters.get("q2")).containsOnly("v2");
}
 
Example #21
Source File: OAuth2CredentialProvider.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private OAuth2CredentialProvider(final String id, final OAuth2ConnectionFactory<S> connectionFactory, final Applicator<AccessGrant> applicator,
    final Map<String, String> additionalQueryParameters, final boolean configured) {
    this.id = id;
    this.connectionFactory = connectionFactory;
    this.applicator = applicator;
    this.configured = configured;
    this.additionalQueryParameters = additionalQueryParameters.entrySet().stream()
        .collect(Collectors.toMap(Map.Entry::getKey, e -> Collections.singletonList(e.getValue())));
}
 
Example #22
Source File: OAuth2CredentialProvider.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public CredentialFlowState finish(final CredentialFlowState givenFlowState, final URI baseUrl) {
    final OAuth2CredentialFlowState flowState = flowState(givenFlowState);

    final AccessGrant accessGrant = connectionFactory.getOAuthOperations().exchangeForAccess(flowState.getCode(), callbackUrlFor(baseUrl, EMPTY), null);

    return new OAuth2CredentialFlowState.Builder().createFrom(flowState).accessGrant(accessGrant).build();
}
 
Example #23
Source File: OAuth2CredentialFlowState.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public AccessGrant convert(final Map<String, String> value) {
    final String expireTimeString = value.get("expireTime");
    final Long expireTime = Optional.ofNullable(expireTimeString).map(Long::valueOf).orElse(null);

    return new AccessGrant(value.get("accessToken"), value.get("scope"), value.get("refreshToken"), expireTime);
}
 
Example #24
Source File: CredentialsTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAcquireOAuth2Credentials() {
    final OAuth2ConnectionFactory<?> oauth2 = mock(OAuth2ConnectionFactory.class);
    @SuppressWarnings("unchecked")
    final Applicator<AccessGrant> applicator = mock(Applicator.class);
    when(locator.providerWithId("providerId"))
    .thenReturn(new OAuth2CredentialProvider<>("providerId", oauth2, applicator, Collections.emptyMap()));

    when(oauth2.getScope()).thenReturn("scope");
    when(oauth2.generateState()).thenReturn("state-token");
    final OAuth2Operations operations = mock(OAuth2Operations.class);
    when(oauth2.getOAuthOperations()).thenReturn(operations);
    final ArgumentCaptor<OAuth2Parameters> parameters = ArgumentCaptor.forClass(OAuth2Parameters.class);
    when(operations.buildAuthorizeUrl(parameters.capture())).thenReturn("https://provider.io/oauth/authorize");

    final AcquisitionFlow acquisition = credentials.acquire("providerId", URI.create("https://syndesis.io/api/v1/"),
        URI.create("/ui#state"));

    final CredentialFlowState expectedFlowState = new OAuth2CredentialFlowState.Builder().key("state-token")
        .providerId("providerId").redirectUrl("https://provider.io/oauth/authorize")
        .returnUrl(URI.create("/ui#state")).build();

    final AcquisitionFlow expected = new AcquisitionFlow.Builder().type(Type.OAUTH2)
        .redirectUrl("https://provider.io/oauth/authorize").state(expectedFlowState).build();
    assertThat(acquisition).isEqualTo(expected);

    final OAuth2Parameters capturedParameters = parameters.getValue();
    assertThat(capturedParameters.getRedirectUri()).isEqualTo("https://syndesis.io/api/v1/credentials/callback");
    assertThat(capturedParameters.getScope()).isEqualTo("scope");
    assertThat(capturedParameters.getState()).isEqualTo("state-token");
}
 
Example #25
Source File: SalesforceConfiguration.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
protected void additionalApplication(final Connection.Builder mutableConnection,
    final AccessGrant accessGrant) {

    final org.springframework.social.connect.Connection<Salesforce> salesforceConnection = salesforce
        .createConnection(accessGrant);
    final Salesforce salesforceApi = salesforceConnection.getApi();

    final String instanceUrl = salesforceApi.getInstanceUrl();
    Applicator.applyProperty(mutableConnection, "instanceUrl", instanceUrl);
}
 
Example #26
Source File: OAuth2ApplicatorTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldApplyAccessGrants() {
    final SocialProperties properties = new SocialProperties() {
        // quick stub used in the test
    };
    properties.setAppId("appId");
    properties.setAppSecret("appSecret");

    final OAuth2Applicator applicator = new OAuth2Applicator(properties);
    applicator.setAccessTokenProperty("accessTokenProperty");
    applicator.setClientIdProperty("clientIdProperty");
    applicator.setClientSecretProperty("clientSecretProperty");
    applicator.setRefreshTokenProperty("refreshTokenProperty");

    final Connection connection = new Connection.Builder().build();

    final Connection result = applicator.applyTo(connection,
        new AccessGrant("accessToken", "scope", "refreshToken", 1L));

    final Connection expected = new Connection.Builder().putConfiguredProperty("accessTokenProperty", "accessToken")
        .putConfiguredProperty("clientIdProperty", "appId")
        .putConfiguredProperty("clientSecretProperty", "appSecret")
        .putConfiguredProperty("refreshTokenProperty", "refreshToken").build();

    assertThat(result).isEqualToIgnoringGivenFields(expected, "lastUpdated");
    assertThat(result.getLastUpdated()).isPresent();
}
 
Example #27
Source File: WeixinOAuth2Template.java    From pre with GNU General Public License v3.0 5 votes vote down vote up
@Override
public AccessGrant exchangeForAccess(String authorizationCode, String redirectUri,
                                     MultiValueMap<String, String> parameters) {

    System.out.println(redirectUri);
    StringBuilder accessTokenRequestUrl = new StringBuilder(accessTokenUrl);

    accessTokenRequestUrl.append("?appid="+clientId);
    accessTokenRequestUrl.append("&secret="+clientSecret);
    accessTokenRequestUrl.append("&code="+authorizationCode);
    accessTokenRequestUrl.append("&grant_type=authorization_code");
    accessTokenRequestUrl.append("&redirect_uri="+redirectUri);

    return getAccessToken(accessTokenRequestUrl);
}
 
Example #28
Source File: WechatConnectionFactory.java    From cola with MIT License 5 votes vote down vote up
/**
 * 由于微信的openId是和accessToken一起返回的,所以在这里直接根据accessToken设置providerUserId即可,不用像QQ那样通过QQAdapter来获取
 */
@Override
protected String extractProviderUserId(AccessGrant accessGrant) {
    if(accessGrant instanceof WechatAccessGrant) {
        return ((WechatAccessGrant)accessGrant).getOpenId();
    }
    return null;
}
 
Example #29
Source File: WechatOAuth2Template.java    From cola with MIT License 5 votes vote down vote up
@Override
public AccessGrant exchangeForAccess(String authorizationCode, String redirectUri,
									 MultiValueMap<String, String> parameters) {

	StringBuilder accessTokenRequestUrl = new StringBuilder(accessTokenUrl);

	accessTokenRequestUrl.append("?appid=" + clientId);
	accessTokenRequestUrl.append("&secret=" + clientSecret);
	accessTokenRequestUrl.append("&code=" + authorizationCode);
	accessTokenRequestUrl.append("&grant_type=authorization_code");
	accessTokenRequestUrl.append("&redirect_uri=" + redirectUri);

	return getAccessToken(accessTokenRequestUrl);
}
 
Example #30
Source File: WechatOAuth2Template.java    From cola with MIT License 5 votes vote down vote up
@Override
public AccessGrant refreshAccess(String refreshToken, MultiValueMap<String, String> additionalParameters) {

	StringBuilder refreshTokenUrl = new StringBuilder(REFRESH_TOKEN_URL);

	refreshTokenUrl.append("?appid=" + clientId);
	refreshTokenUrl.append("&grant_type=refresh_token");
	refreshTokenUrl.append("&refresh_token=" + refreshToken);

	return getAccessToken(refreshTokenUrl);
}