org.springframework.security.oauth2.client.token.AccessTokenRequest Java Examples

The following examples show how to use org.springframework.security.oauth2.client.token.AccessTokenRequest. 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: CustomImplicitAccessTokenProvider.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
private Map<String, String> getParametersForTokenRequest(
        ImplicitResourceDetails resource, AccessTokenRequest request) {

    Map<String, String> queryString = new HashMap<String, String>();
    queryString.put("response_type", "token");
    queryString.put("client_id", resource.getClientId());

    if (resource.isScoped()) {
        queryString.put("scope",
                resource.getScope().stream().reduce((a, b) -> a + " " + b)
                        .get());
    }

    String redirectUri = resource.getRedirectUri(request);
    if (redirectUri == null) {
        throw new IllegalStateException(
                "No redirect URI available in request");
    }
    queryString.put("redirect_uri", redirectUri);

    return queryString;

}
 
Example #2
Source File: SmartlingAuthorizationCodeAccessTokenProvider.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest accessTokenRequest) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException {


    logger.debug("Get access token");
    Map<String, String> request = new HashMap<>();
    request.put("userIdentifier", details.getClientId());
    request.put("userSecret", details.getClientSecret());

    DefaultOAuth2AccessToken defaultOAuth2AccessToken = null;
    try {
        DateTime now = getNowForToken();
        AuthenticationResponse authenticationResponse = restTemplate.postForObject(details.getAccessTokenUri(), request, AuthenticationResponse.class);
        defaultOAuth2AccessToken = getDefaultOAuth2AccessToken(now, authenticationResponse);
    } catch (Exception e) {
        String msg = "Can't get Smartling token";
        logger.debug(msg, e);
        throw new OAuth2AccessDeniedException(msg, details, e);
    }

    return defaultOAuth2AccessToken;
}
 
Example #3
Source File: SmartlingAuthorizationCodeAccessTokenProvider.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest accessTokenRequest) throws UserRedirectRequiredException {

    logger.debug("Get refresh token");

    SmartlingOAuth2ProtectedResourceDetails smartlingOAuth2ProtectedResourceDetails = (SmartlingOAuth2ProtectedResourceDetails) resource;
    Map<String, String> request = new HashMap<>();
    request.put("refreshToken", refreshToken.getValue());

    DefaultOAuth2AccessToken defaultOAuth2AccessToken = null;
    try {
        DateTime now = getNowForToken();
        AuthenticationResponse authenticationResponse = restTemplate.postForObject(smartlingOAuth2ProtectedResourceDetails.getRefreshUri(), request, AuthenticationResponse.class);
        defaultOAuth2AccessToken = getDefaultOAuth2AccessToken(now, authenticationResponse);
    } catch (Exception e) {
        String msg = "Can't get Smartling refresh token";
        logger.debug(msg, e);
        throw new OAuth2AccessDeniedException(msg, resource, e);
    }

    return defaultOAuth2AccessToken;
}
 
Example #4
Source File: IHealthShim.java    From shimmer with Apache License 2.0 6 votes vote down vote up
public IHealthAuthorizationCodeAccessTokenProvider() {

            this.setTokenRequestEnhancer(new RequestEnhancer() {

                @Override
                public void enhance(AccessTokenRequest request,
                        OAuth2ProtectedResourceDetails resource,
                        MultiValueMap<String, String> form, HttpHeaders headers) {

                    form.set("client_id", resource.getClientId());
                    form.set("client_secret", resource.getClientSecret());
                    form.set("redirect_uri", getDefaultRedirectUrl());
                    form.set("state", request.getStateKey());
                }
            });
        }
 
Example #5
Source File: FitbitAccessTokenRequestEnhancer.java    From shimmer with Apache License 2.0 6 votes vote down vote up
@Override
public void enhance(
        AccessTokenRequest request,
        OAuth2ProtectedResourceDetails resource,
        MultiValueMap<String, String> form,
        HttpHeaders headers) {

    form.set("client_id", resource.getClientId());

    /*
       Fitbit requires the redirect_uri to be specified if it was specified in the authorization request.
       It doesn't require the state parameter, even though the documentation says otherwise.
      */
    // TODO this won't work if a redirect URL is specified in the authorization initiation request because
    // Fitbit will reject the authorization code exchange if the redirect_uri parameters of the authorization request
    // and access token request don't match. This needs to be loaded from request scope instead.
    form.set("redirect_uri", deploymentSettings.getRedirectUrl(FitbitShim.SHIM_KEY));
}
 
Example #6
Source File: OAuth2TokenRequestFilter.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public OAuth2AccessToken load(TokenRequestDto requestDto) {
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource);
    restTemplate.setAccessTokenProvider(tokenProvider);
    if (requestDto.getCode() != null) {
        AccessTokenRequest tokenRequest = restTemplate.getOAuth2ClientContext().getAccessTokenRequest();
        tokenRequest.setCurrentUri(requestDto.getRedirectUri());
        tokenRequest.setAuthorizationCode(requestDto.getCode());
    }
    try {
        return restTemplate.getAccessToken();
    } catch (OAuth2Exception e) {
        throw new BadCredentialsException("Could not obtain access token", e);
    }
}
 
Example #7
Source File: MyOAuth2RestTemplate.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
protected OAuth2AccessToken acquireAccessToken(OAuth2ClientContext oauth2Context) throws UserRedirectRequiredException {
    AccessTokenRequest accessTokenRequest = oauth2Context.getAccessTokenRequest();
    if (accessTokenRequest != null) {
        System.out.println("accesstokeRequest == " + accessTokenRequest.getCurrentUri());
    }
    if(accessTokenRequest == null) {
        throw new AccessTokenRequiredException("No OAuth 2 security context has been established. Unable to access resource '" + this.resource.getId() + "'.", this.resource);
    } else {
        String stateKey = accessTokenRequest.getStateKey();
        if(stateKey != null) {
            System.out.println("stateKey == " + stateKey);
            accessTokenRequest.setPreservedState(oauth2Context.removePreservedState(stateKey));
        }

        OAuth2AccessToken existingToken = oauth2Context.getAccessToken();
        if(existingToken != null) {
            accessTokenRequest.setExistingToken(existingToken);
        }

        OAuth2AccessToken accessToken = null;
        accessToken = this.accessTokenProvider.obtainAccessToken(this.resource, accessTokenRequest);
        if(accessToken != null && accessToken.getValue() != null) {
            oauth2Context.setAccessToken(accessToken);
            return accessToken;
        } else {
            throw new IllegalStateException("Access token provider returned a null access token, which is illegal according to the contract.");
        }
    }
}
 
Example #8
Source File: OAuth2FeignRequestInterceptor.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
/**
 * Try to acquire the token using a access token provider.
 * @return valid access token
 * @throws UserRedirectRequiredException in case the user needs to be redirected to an
 * approval page or login page
 */
protected OAuth2AccessToken acquireAccessToken()
		throws UserRedirectRequiredException {
	AccessTokenRequest tokenRequest = oAuth2ClientContext.getAccessTokenRequest();
	if (tokenRequest == null) {
		throw new AccessTokenRequiredException(
				"Cannot find valid context on request for resource '"
						+ resource.getId() + "'.",
				resource);
	}
	String stateKey = tokenRequest.getStateKey();
	if (stateKey != null) {
		tokenRequest.setPreservedState(
				oAuth2ClientContext.removePreservedState(stateKey));
	}
	OAuth2AccessToken existingToken = oAuth2ClientContext.getAccessToken();
	if (existingToken != null) {
		oAuth2ClientContext.setAccessToken(existingToken);
	}
	OAuth2AccessToken obtainableAccessToken;
	obtainableAccessToken = accessTokenProvider.obtainAccessToken(resource,
			tokenRequest);
	if (obtainableAccessToken == null || obtainableAccessToken.getValue() == null) {
		throw new IllegalStateException(
				" Access token provider returned a null token, which is illegal according to the contract.");
	}
	oAuth2ClientContext.setAccessToken(obtainableAccessToken);
	return obtainableAccessToken;
}
 
Example #9
Source File: MockAccessTokenProvider.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2AccessToken obtainAccessToken(
		OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails,
		AccessTokenRequest accessTokenRequest) throws UserRedirectRequiredException,
		UserApprovalRequiredException, AccessDeniedException {
	return token;
}
 
Example #10
Source File: MockAccessTokenProvider.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(
		OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails,
		OAuth2RefreshToken oAuth2RefreshToken, AccessTokenRequest accessTokenRequest)
		throws UserRedirectRequiredException {
	return null;
}
 
Example #11
Source File: MockOAuth2ClientContext.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
@Override
public AccessTokenRequest getAccessTokenRequest() {
	DefaultAccessTokenRequest tokenRequest = new DefaultAccessTokenRequest(
			new HashMap<String, String[]>());
	tokenRequest.setExistingToken(new DefaultOAuth2AccessToken(value));
	return tokenRequest;
}
 
Example #12
Source File: OAuth2FeignRequestInterceptorTests.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
@Test
public void applyAuthorizationHeaderOnlyOnce() {
	OAuth2ClientContext oAuth2ClientContext = mock(OAuth2ClientContext.class);
	when(oAuth2ClientContext.getAccessToken())
			.thenReturn(new MockOAuth2AccessToken("MOCKED_TOKEN"));

	OAuth2FeignRequestInterceptor oAuth2FeignRequestInterceptor = new OAuth2FeignRequestInterceptor(
			oAuth2ClientContext, new BaseOAuth2ProtectedResourceDetails());

	oAuth2FeignRequestInterceptor.apply(requestTemplate);

	// First idempotent call failed, retry mechanism kicks in, and token has expired
	// in the meantime

	OAuth2AccessToken expiredAccessToken = mock(OAuth2AccessToken.class);
	when(expiredAccessToken.isExpired()).thenReturn(true);
	when(oAuth2ClientContext.getAccessToken()).thenReturn(expiredAccessToken);
	AccessTokenRequest accessTokenRequest = mock(AccessTokenRequest.class);
	when(oAuth2ClientContext.getAccessTokenRequest()).thenReturn(accessTokenRequest);
	OAuth2AccessToken newToken = new MockOAuth2AccessToken("Fancy");
	oAuth2FeignRequestInterceptor
			.setAccessTokenProvider(new MockAccessTokenProvider(newToken));

	oAuth2FeignRequestInterceptor.apply(requestTemplate);

	Map<String, Collection<String>> headers = requestTemplate.headers();
	Assert.assertTrue("RequestTemplate must have a Authorization header",
			headers.containsKey("Authorization"));
	Assert.assertThat("Authorization must have a extract of Fancy",
			headers.get("Authorization"), hasSize(1));
	Assert.assertThat("Authorization must have a extract of Fancy",
			headers.get("Authorization"), contains("Bearer Fancy"));
}
 
Example #13
Source File: RunkeeperShim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
public void enhance(AccessTokenRequest request,
        OAuth2ProtectedResourceDetails resource,
        MultiValueMap<String, String> form, HttpHeaders headers) {

    // TODO code?
    form.set("client_id", resource.getClientId());
    form.set("client_secret", resource.getClientSecret());
    form.set("grant_type", resource.getGrantType());
    form.set("redirect_uri", getDefaultRedirectUrl());
}
 
Example #14
Source File: OAuth2Shim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
public AuthorizationRequestParameters getAuthorizationRequestParameters(
        String username,
        Map<String, String> additionalParameters)
        throws ShimException {

    OAuth2RestOperations restTemplate = restTemplate();

    try {
        // TODO replace with restTemplate.getAccessToken();
        trigger(restTemplate, getTriggerDataRequest());

        // if no exception has been thrown, assume that the current authorization is valid
        return AuthorizationRequestParameters.authorized();
    }
    catch (UserRedirectRequiredException e) {
        // if an exception was thrown it means a redirect is required
        AccessTokenRequest accessTokenRequest = restTemplate.getOAuth2ClientContext().getAccessTokenRequest();

        String stateKey = accessTokenRequest.getStateKey();

        /**
         * Build an authorization request from the exception
         * parameters. We also serialize spring's accessTokenRequest.
         */
        AuthorizationRequestParameters authRequestParams = new AuthorizationRequestParameters();
        authRequestParams.setRedirectUri(e.getRedirectUri());
        authRequestParams.setStateKey(e.getStateKey());
        authRequestParams.setAuthorizationUrl(getAuthorizationUrl(e, additionalParameters));
        authRequestParams.setSerializedRequest(SerializationUtils.serialize(accessTokenRequest));
        authRequestParams.setStateKey(stateKey);
        authRequestParams.setRequestParams(additionalParameters);

        return authorizationRequestParametersRepo.save(authRequestParams);
    }
}
 
Example #15
Source File: JawboneShim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
public void enhance(AccessTokenRequest request,
        OAuth2ProtectedResourceDetails resource,
        MultiValueMap<String, String> form, HttpHeaders headers) {
    form.set("client_id", resource.getClientId());
    form.set("client_secret", resource.getClientSecret());
}
 
Example #16
Source File: MisfitShim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
public void enhance(AccessTokenRequest request, OAuth2ProtectedResourceDetails resource,
        MultiValueMap<String, String> form, HttpHeaders headers) {

    form.set("client_id", resource.getClientId());
    form.set("client_secret", resource.getClientSecret());
    form.set("redirect_uri", getDefaultRedirectUrl());
}
 
Example #17
Source File: MovesShim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
public void enhance(
        AccessTokenRequest request,
        OAuth2ProtectedResourceDetails resource,
        MultiValueMap<String, String> form,
        HttpHeaders headers) {

    form.set("client_id", resource.getClientId());
    form.set("client_secret", resource.getClientSecret());
    form.set("redirect_uri", getDefaultRedirectUrl());
}
 
Example #18
Source File: GoogleFitShim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(
        OAuth2ProtectedResourceDetails resource,
        OAuth2RefreshToken refreshToken, AccessTokenRequest request)
        throws UserRedirectRequiredException,
        OAuth2AccessDeniedException {

    OAuth2AccessToken accessToken = super.refreshAccessToken(resource, refreshToken, request);
    // Google does not replace refresh tokens, so we need to hold on to the existing refresh token...
    if (accessToken.getRefreshToken() == null) {
        ((DefaultOAuth2AccessToken) accessToken).setRefreshToken(refreshToken);
    }
    return accessToken;
}
 
Example #19
Source File: GoogleFitShim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
public void enhance(AccessTokenRequest request,
        OAuth2ProtectedResourceDetails resource,
        MultiValueMap<String, String> form, HttpHeaders headers) {

    form.set("client_id", resource.getClientId());
    form.set("client_secret", resource.getClientSecret());
    if (request.getStateKey() != null) {
        form.set("redirect_uri", getDefaultRedirectUrl());
    }
}
 
Example #20
Source File: OauthClientApplication.java    From Spring with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/execute")
public String execute(Principal principal) throws URISyntaxException {
    final User user = (User) ((Authentication) principal).getPrincipal();
    final URI uri = new URI("http://localhost:7070/resource/endpoint");

    final RequestEntity<String> requestEntity = new RequestEntity<>(HttpMethod.GET, uri);
    final AccessTokenRequest accessTokenRequest = oAuth2RestTemplate.getOAuth2ClientContext().getAccessTokenRequest();
    accessTokenRequest.set("username", user.getUsername());
    accessTokenRequest.set("password", user.getPassword());

    return oAuth2RestTemplate.exchange(requestEntity, String.class).getBody();
}
 
Example #21
Source File: OpenIdAccessTokenProvider.java    From cola with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest request) throws UserRedirectRequiredException {
	MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
	form.add("grant_type", "refresh_token");
	form.add("refresh_token", refreshToken.getValue());
	return retrieveToken(request, resource, form, new HttpHeaders());
}
 
Example #22
Source File: OpenIdAccessTokenProvider.java    From cola with MIT License 5 votes vote down vote up
private MultiValueMap<String, String> getParametersForTokenRequest(OpenIdResourceDetails resource, AccessTokenRequest request) {

		MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
		form.set("grant_type", "openid");
		form.set("openid", resource.getOpenId());
		form.set("provider", resource.getProvider());
		form.putAll(request);

		if (resource.isScoped()) {

			StringBuilder builder = new StringBuilder();
			List<String> scope = resource.getScope();

			if (scope != null) {
				Iterator<String> scopeIt = scope.iterator();
				while (scopeIt.hasNext()) {
					builder.append(scopeIt.next());
					if (scopeIt.hasNext()) {
						builder.append(' ');
					}
				}
			}

			form.set("scope", builder.toString());
		}

		return form;

	}
 
Example #23
Source File: SmsAccessTokenProvider.java    From cola with MIT License 5 votes vote down vote up
private MultiValueMap<String, String> getParametersForTokenRequest(SmsResourceDetails resource, AccessTokenRequest request) {

		MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
		form.set("grant_type", "sms");
		form.set("phoneNumber", resource.getPhoneNumber());
		form.set("credential", resource.getCredential());
		form.putAll(request);

		if (resource.isScoped()) {

			StringBuilder builder = new StringBuilder();
			List<String> scope = resource.getScope();

			if (scope != null) {
				Iterator<String> scopeIt = scope.iterator();
				while (scopeIt.hasNext()) {
					builder.append(scopeIt.next());
					if (scopeIt.hasNext()) {
						builder.append(' ');
					}
				}
			}

			form.set("scope", builder.toString());
		}

		return form;

	}
 
Example #24
Source File: AcAccessTokenProvider.java    From cola with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest request) throws UserRedirectRequiredException {
	MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
	form.add("grant_type", "refresh_token");
	form.add("refresh_token", refreshToken.getValue());
	return retrieveToken(request, resource, form, new HttpHeaders());
}
 
Example #25
Source File: AcAccessTokenProvider.java    From cola with MIT License 5 votes vote down vote up
private MultiValueMap<String, String> getParametersForTokenRequest(AcResourceDetails resource, AccessTokenRequest request) {

		MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
		form.set("grant_type", "ac");
		form.set("authorizationCode", resource.getAuthorizationCode());
		form.set("provider", resource.getProvider());
		form.putAll(request);

		if (resource.isScoped() && resource.getScope() != null) {
			form.set("scope", String.join(" ", resource.getScope()));
		}
		return form;

	}
 
Example #26
Source File: OAuthClient.java    From cf-java-client-sap with Apache License 2.0 5 votes vote down vote up
protected OAuth2AccessToken createToken() {
    OAuth2ProtectedResourceDetails resource = getResourceDetails(credentials.getEmail(), credentials.getPassword(),
                                                                 credentials.getClientId(), credentials.getClientSecret());
    AccessTokenRequest request = createAccessTokenRequest(credentials.getEmail(), credentials.getPassword());

    ResourceOwnerPasswordAccessTokenProvider provider = createResourceOwnerPasswordAccessTokenProvider();
    try {
        return provider.obtainAccessToken(resource, request);
    } catch (OAuth2AccessDeniedException oauthEx) {
        HttpStatus status = HttpStatus.valueOf(oauthEx.getHttpErrorCode());
        throw new CloudOperationException(status, oauthEx.getMessage(), oauthEx.getSummary());
    }
}
 
Example #27
Source File: OAuthClient.java    From cf-java-client-sap with Apache License 2.0 5 votes vote down vote up
protected OAuth2AccessToken refreshToken() {
    OAuth2ProtectedResourceDetails resource = getResourceDetails(credentials.getEmail(), credentials.getPassword(),
                                                                 credentials.getClientId(), credentials.getClientSecret());
    AccessTokenRequest request = createAccessTokenRequest(credentials.getEmail(), credentials.getPassword());

    ResourceOwnerPasswordAccessTokenProvider provider = createResourceOwnerPasswordAccessTokenProvider();

    return provider.refreshAccessToken(resource, token.getRefreshToken(), request);
}
 
Example #28
Source File: PoPTokenRequestEnhancer.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public void enhance(AccessTokenRequest request,
    OAuth2ProtectedResourceDetails resource,
    MultiValueMap<String, String> form,
    HttpHeaders headers) {
    form.add("public_key", keyPairManager.createJWK().toJSONString());
}
 
Example #29
Source File: CustomImplicitAccessTokenProvider.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken obtainAccessToken(
        OAuth2ProtectedResourceDetails details, AccessTokenRequest request)
        throws RuntimeException {

    ImplicitResourceDetails resource = (ImplicitResourceDetails) details;

    Map<String, String> requestParameters = getParametersForTokenRequest(
            resource, request);

    UserRedirectRequiredException redirectException = new UserRedirectRequiredException(
            resource.getUserAuthorizationUri(), requestParameters);

    throw redirectException;
}
 
Example #30
Source File: CustomImplicitAccessTokenProvider.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(
        OAuth2ProtectedResourceDetails resource,
        OAuth2RefreshToken refreshToken, AccessTokenRequest request)
        throws UserRedirectRequiredException {
    return null;
}