Java Code Examples for org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails

The following examples show how to use org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails. These examples are extracted from open source projects. 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
@Override
public void authenticate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext clientContext,
        ClientHttpRequest request) {

    OAuth2AccessToken accessToken = clientContext.getAccessToken();
    if (accessToken == null) {
        throw new AccessTokenRequiredException(resource);
    }

    String tokenType = accessToken.getTokenType();

    if (!StringUtils.hasText(tokenType) || tokenType.equalsIgnoreCase(OAuth2AccessToken.BEARER_TYPE)) {
        tokenType = OAuth2AccessToken.BEARER_TYPE; // we'll assume basic bearer token type if none is specified.
    }

    request.getHeaders().set("Authorization", String.format("%s %s", tokenType, accessToken.getValue()));
}
 
Example 2
Source Project: shimmer   Source File: IHealthShim.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected String getAuthorizationUrl(UserRedirectRequiredException exception, Map<String, String> addlParameters) {

    final OAuth2ProtectedResourceDetails resource = getResource();

    UriComponentsBuilder callBackUriBuilder = UriComponentsBuilder.fromUriString(getDefaultRedirectUrl())
            .queryParam("state", exception.getStateKey());

    UriComponentsBuilder authorizationUriBuilder = UriComponentsBuilder.fromUriString(exception.getRedirectUri())
            .queryParam("client_id", resource.getClientId())
            .queryParam("response_type", "code")
            .queryParam("APIName", Joiner.on(' ').join(resource.getScope()))
            .queryParam("RequiredAPIName", Joiner.on(' ').join(resource.getScope()))
            .queryParam("redirect_uri", callBackUriBuilder.build().toString());

    return authorizationUriBuilder.build().encode().toString();
}
 
Example 3
@Test
public void shouldSaveAccessToken() {
    //Given
    final OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails = oAuth2ProtectedResourceDetailsBuilder().build();
    final TestingAuthenticationToken authentication = new TestingAuthenticationToken(userBuilder().build(), string().next());
    final OAuth2AccessToken oAuth2AccessToken = oAuth2AccessTokenBuilder().build();

    //And
    final String authenticationId = string().next();
    given(keyGenerator.extractKey(oAuth2ProtectedResourceDetails, authentication)).willReturn(authenticationId);

    //When
    mongoClientTokenServices.saveAccessToken(oAuth2ProtectedResourceDetails, authentication, oAuth2AccessToken);

    //Then
    verify(keyGenerator, atLeastOnce()).extractKey(oAuth2ProtectedResourceDetails, authentication);
    verify(mongoOAuth2ClientTokenRepository).save(any(MongoOAuth2ClientToken.class));
    verify(mongoOAuth2ClientTokenRepository).deleteByAuthenticationId(authenticationId);
}
 
Example 4
@Override
public void saveAccessToken(
        OAuth2ProtectedResourceDetails resource,
        Authentication authentication, OAuth2AccessToken accessToken) {

    String username = authentication.getPrincipal().toString();
    String shimKey = authentication.getDetails().toString();

    AccessParameters accessParameters =
            accessParametersRepo.findByUsernameAndShimKey(
                    username,
                    shimKey,
                    new Sort(Sort.Direction.DESC, "dateCreated"));

    if (accessParameters == null) {
        accessParameters = new AccessParameters();
        accessParameters.setUsername(username);
        accessParameters.setShimKey(shimKey);
    }

    accessParameters.setSerializedToken(SerializationUtils.serialize(accessToken));

    accessParametersRepo.save(accessParameters);
}
 
Example 5
Source Project: OAuth-2.0-Cookbook   Source File: ClientConfiguration.java    License: MIT License 6 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails authorizationCode() {
    AuthorizationCodeResourceDetails resourceDetails = new AuthorizationCodeResourceDetails();

    //@formatter:off
    resourceDetails.setId("oauth2server");
    resourceDetails.setTokenName("oauth_token");
    resourceDetails.setClientId("clientapp");
    resourceDetails.setClientSecret("123456");
    resourceDetails.setAccessTokenUri("http://localhost:8080/oauth/token");
    resourceDetails.setUserAuthorizationUri("http://localhost:8080/oauth/authorize");
    resourceDetails.setScope(Arrays.asList("read_profile"));
    resourceDetails.setPreEstablishedRedirectUri(("http://localhost:9000/callback"));
    resourceDetails.setUseCurrentUri(false);
    resourceDetails.setClientAuthenticationScheme(AuthenticationScheme.header);
    //@formatter:on

    return resourceDetails;
}
 
Example 6
Source Project: OAuth-2.0-Cookbook   Source File: ClientConfiguration.java    License: MIT License 6 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails authorizationCode() {
    AuthorizationCodeResourceDetails resourceDetails = new AuthorizationCodeResourceDetails();

    //@formatter:off
    resourceDetails.setId("oauth2server");
    resourceDetails.setTokenName("oauth_token");
    resourceDetails.setClientId("clientapp");
    resourceDetails.setClientSecret("123456");
    resourceDetails.setAccessTokenUri("http://localhost:8080/oauth/token");
    resourceDetails.setUserAuthorizationUri("http://localhost:8080/oauth/authorize");
    resourceDetails.setScope(Arrays.asList("read_profile"));
    resourceDetails.setPreEstablishedRedirectUri(("http://localhost:9000/callback"));
    resourceDetails.setUseCurrentUri(false);
    resourceDetails.setClientAuthenticationScheme(AuthenticationScheme.header);
    //@formatter:on

    return resourceDetails;
}
 
Example 7
Source Project: shimmer   Source File: FitbitShim.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected String getAuthorizationUrl(
        UserRedirectRequiredException exception,
        Map<String, String> additionalParameters) {

    final OAuth2ProtectedResourceDetails resource = getResource();

    // TODO this override won't work, see FitbitAccessTokenRequestEnhancer for details
    String redirectUrl = additionalParameters.get(REDIRECT_URL_KEY) == null
            ? getDefaultRedirectUrl()
            : additionalParameters.get(REDIRECT_URL_KEY);

    UriComponentsBuilder uriBuilder = UriComponentsBuilder
            .fromUriString(exception.getRedirectUri())
            .queryParam("response_type", "code")
            .queryParam("client_id", resource.getClientId())
            .queryParam("redirect_uri", redirectUrl)
            .queryParam("scope", Joiner.on(" ").join(resource.getScope()))
            .queryParam("state", exception.getStateKey())
            .queryParam("prompt", fitbitClientSettings.getPromptType().getQueryParameterValue());

    return uriBuilder.build().encode().toUriString();
}
 
Example 8
Source Project: OAuth-2.0-Cookbook   Source File: ClientConfiguration.java    License: MIT License 6 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails passwordResourceDetails() {
    //@formatter:off
ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();

details.setId("oauth2server");
details.setTokenName("oauth_token");
details.setClientId("clientadmin");
details.setClientSecret("123");
details.setAccessTokenUri("http://localhost:8080/oauth/token");
details.setScope(Arrays.asList("admin"));

details.setClientAuthenticationScheme(AuthenticationScheme.header);
//@formatter:on

    return details;
}
 
Example 9
Source Project: OAuth-2.0-Cookbook   Source File: ClientConfiguration.java    License: MIT License 6 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails passwordResourceDetails() {
    //@formatter:off
    ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();

    resourceDetails.setId("oauth2server");
    resourceDetails.setTokenName("oauth_token");
    resourceDetails.setClientId("clientapp");
    resourceDetails.setClientSecret("123456");
    resourceDetails.setAccessTokenUri("http://localhost:8080/oauth/token");
    resourceDetails.setScope(Arrays.asList("read_profile"));

    resourceDetails.setClientAuthenticationScheme(AuthenticationScheme.header);
    //@formatter:on

    return resourceDetails;
}
 
Example 10
public MyOAuth2RestTemplate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext context) {
    super(resource, context);
    this.accessTokenProvider = new MyAccessTokenProviderChain(Arrays.asList(new AccessTokenProvider[]{new MyAuthorizationCodeAccessTokenProvider(),
            new ImplicitAccessTokenProvider(),
            new ResourceOwnerPasswordAccessTokenProvider(),
            new ClientCredentialsAccessTokenProvider()}));
    this.retryBadAccessTokens = true;
    this.authenticator = new DefaultOAuth2RequestAuthenticator();
    if(resource == null) {
        throw new IllegalArgumentException("An OAuth2 resource must be supplied.");
    } else {
        this.resource = resource;
        this.context = context;
        this.setErrorHandler(new OAuth2ErrorHandler(resource));
    }
}
 
Example 11
@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 12
@Test
public void shouldGetAccessToken() {
    //Given
    final OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails = oAuth2ProtectedResourceDetailsBuilder().build();
    final TestingAuthenticationToken authentication = new TestingAuthenticationToken(userBuilder().build(), string().next());

    //And
    final String authenticationId = string().next();
    given(keyGenerator.extractKey(oAuth2ProtectedResourceDetails, authentication)).willReturn(authenticationId);

    //And
    final OAuth2AccessToken expectedToken = oAuth2AccessTokenBuilder().build();
    given(mongoOAuth2ClientTokenRepository.findByAuthenticationId(authenticationId)).willReturn(mongoOAuth2ClientTokenBuilder().token(expectedToken).build());

    //When
    final OAuth2AccessToken accessToken = mongoClientTokenServices.getAccessToken(oAuth2ProtectedResourceDetails, authentication);

    //Then
    assertThat(accessToken).isEqualTo(expectedToken);
}
 
Example 13
Source Project: shimmer   Source File: GoogleFitShim.java    License: 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 14
@Override
public OAuth2AccessToken refreshAccessToken(
		OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails,
		OAuth2RefreshToken oAuth2RefreshToken, AccessTokenRequest accessTokenRequest)
		throws UserRedirectRequiredException {
	return null;
}
 
Example 15
Source Project: shimmer   Source File: MisfitShim.java    License: 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 16
Source Project: Spring   Source File: OauthClientApplication.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails() {
    final ResourceOwnerPasswordResourceDetails details = new ResourceOwnerPasswordResourceDetails();
    details.setAccessTokenUri("http://localhost:9090/oauth/token");
    details.setClientId("webapp");
    details.setClientSecret("websecret");
    details.setGrantType("password");

    return details;
}
 
Example 17
Source Project: oauth2lab   Source File: OAuth2Configuration.java    License: MIT License 5 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails authorizationCode() {
    AuthorizationCodeResourceDetails details =
        new AuthorizationCodeResourceDetails();
    details.setId("oauth2server");
    details.setClientId("clientapp");
    details.setClientSecret("112233");
    details.setUseCurrentUri(true);
    details.setUserAuthorizationUri("http://localhost:8080/oauth/authorize");
    details.setAccessTokenUri("http://localhost:8080/oauth/token");
    return details;
}
 
Example 18
Source Project: shimmer   Source File: MovesShim.java    License: 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 19
Source Project: shimmer   Source File: MisfitShim.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected String getAuthorizationUrl(UserRedirectRequiredException exception, Map<String, String> addlParameters) {

    final OAuth2ProtectedResourceDetails resource = getResource();

    UriComponentsBuilder uriBuilder = UriComponentsBuilder
            .fromUriString(exception.getRedirectUri())
            .queryParam("state", exception.getStateKey())
            .queryParam("client_id", resource.getClientId())
            .queryParam("response_type", "code")
            .queryParam("scope", Joiner.on(',').join(resource.getScope()))
            .queryParam("redirect_uri", getDefaultRedirectUrl());

    return uriBuilder.build().encode().toUriString();
}
 
Example 20
@Bean
@ConditionalOnMissingBean
public UserInfoRestTemplateFactory userInfoRestTemplateFactory(
		ObjectProvider<List<UserInfoRestTemplateCustomizer>> customizers,
		ObjectProvider<OAuth2ProtectedResourceDetails> details,
		ObjectProvider<OAuth2ClientContext> oauth2ClientContext) {
	return new DefaultUserInfoRestTemplateFactory(customizers, details, oauth2ClientContext);
}
 
Example 21
@Test
public void withRestTemplate() {
	OAuth2ProtectedResourceDetails resource = new AuthorizationCodeResourceDetails();
	OAuth2ClientContext context = new DefaultOAuth2ClientContext();
	DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken("FOO");
	token.setRefreshToken(new DefaultExpiringOAuth2RefreshToken("BAR", new Date(0L)));
	context.setAccessToken(token);
	this.services.setRestTemplate(new OAuth2RestTemplate(resource, context));
	assertThat(this.services.loadAuthentication("FOO").getName()).isEqualTo("me");
	assertThat(context.getAccessToken().getValue()).isEqualTo("FOO");
	// The refresh token is still intact
	assertThat(context.getAccessToken().getRefreshToken()).isEqualTo(token.getRefreshToken());
}
 
Example 22
@Test
public void withRestTemplateChangesState() {
	OAuth2ProtectedResourceDetails resource = new AuthorizationCodeResourceDetails();
	OAuth2ClientContext context = new DefaultOAuth2ClientContext();
	context.setAccessToken(new DefaultOAuth2AccessToken("FOO"));
	this.services.setRestTemplate(new OAuth2RestTemplate(resource, context));
	assertThat(this.services.loadAuthentication("BAR").getName()).isEqualTo("me");
	assertThat(context.getAccessToken().getValue()).isEqualTo("BAR");
}
 
Example 23
Source Project: cf-java-client-sap   Source File: OAuthClient.java    License: 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 24
Source Project: cf-java-client-sap   Source File: OAuthClient.java    License: 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 25
Source Project: cf-java-client-sap   Source File: OAuthClient.java    License: Apache License 2.0 5 votes vote down vote up
private OAuth2ProtectedResourceDetails getResourceDetails(String username, String password, String clientId, String clientSecret) {
    ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
    resource.setUsername(username);
    resource.setPassword(password);

    resource.setClientId(clientId);
    resource.setClientSecret(clientSecret);
    resource.setId(clientId);
    resource.setClientAuthenticationScheme(AuthenticationScheme.header);
    resource.setAccessTokenUri(authorizationUrl + "/oauth/token");

    return resource;
}
 
Example 26
Source Project: OAuth-2.0-Cookbook   Source File: FacebookConfiguration.java    License: MIT License 5 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails resourceDetails() {
    AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
    details.setClientId(properties.getClientId());
    details.setClientSecret(properties.getClientSecret());
    details.setUserAuthorizationUri(properties.getAppAuthorizationUri());
    details.setAccessTokenUri(properties.getAppTokenUri());
    details.setPreEstablishedRedirectUri(properties.getRedirectUri());
    details.setScope(Arrays.asList("email", "public_profile"));
    details.setClientAuthenticationScheme(AuthenticationScheme.query);
    details.setUseCurrentUri(false);
    return details;
}
 
Example 27
Source Project: OAuth-2.0-Cookbook   Source File: GoogleConfiguration.java    License: MIT License 5 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails resourceDetails() {
    AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
    details.setClientId(properties.getClientId());
    details.setClientSecret(properties.getClientSecret());

    // URLs retrieved from https://accounts.google.com/.well-known/openid-configuration
    details.setUserAuthorizationUri("https://accounts.google.com/o/oauth2/v2/auth");
    details.setAccessTokenUri("https://www.googleapis.com/oauth2/v4/token");
    details.setPreEstablishedRedirectUri("http://localhost:8080/google/callback");
    details.setScope(Arrays.asList("openid", "email", "profile"));
    details.setUseCurrentUri(false);

    return details;
}
 
Example 28
Source Project: OAuth-2.0-Cookbook   Source File: OAuth2Configuration.java    License: MIT License 5 votes vote down vote up
@Bean
public OAuth2ProtectedResourceDetails authorizationCode() {
    AuthorizationCodeResourceDetails details =
        new AuthorizationCodeResourceDetails();
    details.setId("oauth2server");
    details.setClientId("clientapp");
    details.setClientSecret("123");
    details.setUseCurrentUri(true);
    details.setUserAuthorizationUri("http://localhost:8080/oauth/authorize");
    details.setAccessTokenUri("http://localhost:8080/oauth/token");
    return details;
}
 
Example 29
Source Project: OAuth-2.0-Cookbook   Source File: PoPTokenRequestEnhancer.java    License: 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 30
Source Project: OAuth-2.0-Cookbook   Source File: OAuth2ClientTokenSevices.java    License: MIT License 5 votes vote down vote up
@Override
public void saveAccessToken(OAuth2ProtectedResourceDetails resource,
        Authentication authentication, OAuth2AccessToken accessToken) {
    ClientUser clientUser = getClientUser(authentication);

    clientUser.accessToken = accessToken.getValue();
    clientUser.expirationTime = accessToken.getExpiration().getTime();
    clientUser.additionalInformation = accessToken.getAdditionalInformation();

    users.put(clientUser.username, clientUser);
}