本文整理汇总了Java中org.springframework.social.oauth2.AccessGrant类的典型用法代码示例。如果您正苦于以下问题:Java AccessGrant类的具体用法?Java AccessGrant怎么用?Java AccessGrant使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
AccessGrant类属于org.springframework.social.oauth2包,在下文中一共展示了AccessGrant类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: completeConnection
import org.springframework.social.oauth2.AccessGrant; //导入依赖的package包/类
/**
* Complete the connection to the OAuth2 provider.
*
* @param connectionFactory the service provider's connection factory e.g. FacebookConnectionFactory
* @param request the current web request
* @return a new connection to the service provider
*/
public Connection completeConnection(OAuth2ConnectionFactory<?> connectionFactory, NativeWebRequest request) {
if (connectionFactory.supportsStateParameter()) {
verifyStateParameter(request);
}
String code = request.getParameter("code");
try {
AccessGrant accessGrant = connectionFactory.getOAuthOperations()
.exchangeForAccess(code, callbackUrl(request), null);
return connectionFactory.createConnection(accessGrant);
} catch (HttpClientErrorException e) {
log.warn("HttpClientErrorException while completing connection: " + e.getMessage());
log.warn(" Response body: " + e.getResponseBodyAsString());
throw e;
}
}
示例2: getFacebookConnectionForChannel
import org.springframework.social.oauth2.AccessGrant; //导入依赖的package包/类
public Connection<Facebook> getFacebookConnectionForChannel(NodeRef channelNode)
{
Connection<Facebook> connection = null;
if (nodeService.exists(channelNode)
&& nodeService.hasAspect(channelNode, FacebookPublishingModel.ASPECT_DELIVERY_CHANNEL))
{
String tokenValue = (String) encryptor.decrypt(PublishingModel.PROP_OAUTH2_TOKEN, nodeService.getProperty(
channelNode, PublishingModel.PROP_OAUTH2_TOKEN));
Boolean danceComplete = (Boolean) nodeService.getProperty(channelNode, PublishingModel.PROP_AUTHORISATION_COMPLETE);
if (danceComplete)
{
AccessGrant token = new AccessGrant(tokenValue);
connection = connectionFactory.createConnection(token);
}
}
return connection;
}
示例3: shouldApplyOAuthPropertiesToNewlyCreatedConnections
import org.springframework.social.oauth2.AccessGrant; //导入依赖的package包/类
@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").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"));
}
示例4: shouldApplyAccessGrants
import org.springframework.social.oauth2.AccessGrant; //导入依赖的package包/类
@Test
public void shouldApplyAccessGrants() {
final SocialProperties properties = new SocialProperties() {
};
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();
}
示例5: shouldApplyAdditionalProperties
import org.springframework.social.oauth2.AccessGrant; //导入依赖的package包/类
@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"));
}
示例6: getOrCreateConnection
import org.springframework.social.oauth2.AccessGrant; //导入依赖的package包/类
/**
* Get existing connection or create new one if no connection found or it expired
* @return {@link Connection} actual connection
*/
private Connection<BotFramework> getOrCreateConnection() {
Connection<BotFramework> botFramework = repository.findPrimaryConnection(BotFramework.class);
if(botFramework == null || botFramework.hasExpired()){
synchronized (BotFrameworkReConnectHandler.class) {
botFramework = repository.findPrimaryConnection(BotFramework.class);
if(botFramework == null || botFramework.hasExpired()){
if (botFramework != null) {
repository.removeConnection(botFramework.getKey());
}
botFramework = repository.findPrimaryConnection(BotFramework.class);
if (botFramework == null) {
AccessGrant accessGrant = connectionFactory.getOAuthOperations().authenticateClient(scope);
Connection<BotFramework> connection = connectionFactory.createConnection(accessGrant);
repository.addConnection(connection);
botFramework = repository.findPrimaryConnection(BotFramework.class);
}
}
}
}
return botFramework;
}
示例7: shouldApplyAdditionalProperties
import org.springframework.social.oauth2.AccessGrant; //导入依赖的package包/类
@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(((Connection) mutableConnection.build()).getConfiguredProperties())
.containsExactly(entry("instanceUrl", "https://instance.salesforce.com"));
}
示例8: get
import org.springframework.social.oauth2.AccessGrant; //导入依赖的package包/类
protected AccessGrant get(OidcTokenId id, Callable<AccessGrant> grantLoader) {
// it should be only used to put the exchanged token,
// the refresh should be handled by the CacheLoader
// Don't make it public
Preconditions.checkNotNull(id);
Preconditions.checkNotNull(grantLoader);
Callable<? extends AccessGrant> loggingGrantLoader = () -> {
LOG.debug("Loading and putting new access token for {} into cache", id);
AccessGrant grant = grantLoader.call();
LOG.trace("New access token for {}={}", id, grant.getAccessToken());
return grant;
};
try {
return oauth2TokensCache.get(id, loggingGrantLoader);
} catch (ExecutionException ex) {
throw new OrchestratorException(ex.getCause());
}
}
示例9: getOrGenerateRequester
import org.springframework.social.oauth2.AccessGrant; //导入依赖的package包/类
private Optional<OidcEntity> getOrGenerateRequester() {
if (oidcProperties.isEnabled()) {
OidcEntityId requesterId = oauth2TokenService.generateOidcEntityIdFromCurrentAuth();
OidcEntity requester = oidcEntityRepository
.findByOidcEntityId(requesterId)
.orElseGet(oauth2TokenService::generateOidcEntityFromCurrentAuth);
// exchange token if a refresh token is not yet associated with the user
if (requester.getRefreshToken() == null) {
OidcTokenId currentTokenId = oauth2TokenService.generateTokenIdFromCurrentAuth();
AccessGrant grant = oauth2TokenService.exchangeAccessToken(currentTokenId,
oauth2TokenService.getOAuth2TokenFromCurrentAuth(), OidcProperties.REQUIRED_SCOPES);
OidcRefreshToken token = OidcRefreshToken.fromAccessGrant(currentTokenId, grant);
requester.setRefreshToken(token);
}
return Optional.of(requester);
} else {
return Optional.empty();
}
}
示例10: fromAccessGrant
import org.springframework.social.oauth2.AccessGrant; //导入依赖的package包/类
/**
* Generate a OidcRefreshToken from a token id and a grant.
*
* @param currentTokenId
* the token id
* @param grant
* the grant
* @return the OidcRefreshToken
*/
public static OidcRefreshToken fromAccessGrant(OidcTokenId currentTokenId, AccessGrant grant) {
OidcRefreshToken token = new OidcRefreshToken();
token.setOriginalTokenId(currentTokenId.getJti());
token.setVaule(grant.getRefreshToken());
token.setCreationDate(new Date());
Optional.ofNullable(grant.getScope())
.map(scopeAsString -> scopeAsString.split("\\s+"))
.map(scopes -> Lists.newArrayList(scopes))
.ifPresent(scopes -> token.setScopes(CommonUtils.checkNotNull(scopes)));
JwtUtils.getExpirationTime(JwtUtils.parseJwt(token.getVaule()))
.ifPresent(expirationDate -> token.setExpirationDate(expirationDate));
return token;
}
示例11: addConnection
import org.springframework.social.oauth2.AccessGrant; //导入依赖的package包/类
@Test
public void addConnection() {
Connection<TestFacebookApi> connection = connectionFactory.createConnection(new AccessGrant("123456789", null, "987654321", 3600L));
connectionRepository.addConnection(connection);
Connection<TestFacebookApi> restoredConnection = connectionRepository.getPrimaryConnection(TestFacebookApi.class);
assertEquals(connection, restoredConnection);
assertNewConnection(restoredConnection);
}
示例12: addConnectionDuplicate
import org.springframework.social.oauth2.AccessGrant; //导入依赖的package包/类
@Test(expected = DataIntegrityViolationException.class)
public void addConnectionDuplicate() {
Connection<TestFacebookApi> connection = connectionFactory.createConnection(new AccessGrant("123456789", null, "987654321", 3600L));
connectionRepository.addConnection(connection);
connectionRepository.addConnection(connection);
socialUserConnectionRepository.flush();
}
示例13: loadAuthentication
import org.springframework.social.oauth2.AccessGrant; //导入依赖的package包/类
@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);
}
示例14: create
import org.springframework.social.oauth2.AccessGrant; //导入依赖的package包/类
@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);
@SuppressWarnings({ "unchecked", "rawtypes" })
final Class<MultiValueMap<String, String>> additionalParametersType = (Class) MultiValueMap.class;
final OAuth2Operations operations = spy(new OAuth2Template("testClientId", "testClientSecret",
"https://test/oauth2/authorize", "https://test/oauth2/token"));
doReturn(new AccessGrant("token")).when(operations).exchangeForAccess(Matchers.anyString(),
Matchers.anyString(), Matchers.any(additionalParametersType));
when(connectionFactory.getOAuthOperations()).thenReturn(operations);
return credentialProvider;
}
示例15: shouldReceiveCallbacksFromResourceProviders
import org.springframework.social.oauth2.AccessGrant; //导入依赖的package包/类
@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"));
}