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

The following examples show how to use org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails. 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: AccessParameterClientTokenServices.java    From shimmer with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: MyOAuth2RestTemplate.java    From springboot-security-wechat with Apache License 2.0 6 votes vote down vote up
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 #3
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 #4
Source File: MongoClientTokenServicesTest.java    From spring-security-mongo with MIT License 6 votes vote down vote up
@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 #5
Source File: CaseStandardizingOAuth2RequestAuthenticator.java    From shimmer with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: IHealthShim.java    From shimmer with 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 #7
Source File: ClientConfiguration.java    From OAuth-2.0-Cookbook with 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 #8
Source File: ClientConfiguration.java    From OAuth-2.0-Cookbook with 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 File: MongoClientTokenServicesTest.java    From spring-security-mongo with MIT License 6 votes vote down vote up
@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 #10
Source File: FitbitShim.java    From shimmer with 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 #11
Source File: ClientConfiguration.java    From OAuth-2.0-Cookbook with 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 #12
Source File: ClientConfiguration.java    From OAuth-2.0-Cookbook with 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 #13
Source File: JawboneShim.java    From shimmer with 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", StringUtils.collectionToDelimitedString(resource.getScope(), " "))
            .queryParam("redirect_uri", getDefaultRedirectUrl());

    return uriBuilder.build().encode().toUriString();
}
 
Example #14
Source File: OAuth2ClientTokenSevices.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public void removeAccessToken(OAuth2ProtectedResourceDetails resource,
        Authentication authentication) {
    ClientUser clientUser = getClientUser(authentication);

    clientUser.setAccessToken(null);
    clientUser.setRefreshToken(null);
    clientUser.setAccessTokenValidity(null);

    users.save(clientUser);
}
 
Example #15
Source File: MongoClientTokenServicesTest.java    From spring-security-mongo with MIT License 5 votes vote down vote up
@Test
public void shouldRemoveAccessToken() {
    //Given
    final OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails = oAuth2ProtectedResourceDetailsBuilder().build();
    final TestingAuthenticationToken authentication = new TestingAuthenticationToken(userBuilder().build(), string().next());

    //And
    final String value = string().next();
    when(keyGenerator.extractKey(oAuth2ProtectedResourceDetails, authentication)).thenReturn(value);
    //When
    mongoClientTokenServices.removeAccessToken(oAuth2ProtectedResourceDetails, authentication);

    //Then
    verify(mongoOAuth2ClientTokenRepository).deleteByAuthenticationId(value);
}
 
Example #16
Source File: OAuth2Shim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
public OAuth2ProtectedResourceDetails getResource() {

        AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();

        resource.setAccessTokenUri(getAccessTokenUrl());
        resource.setUserAuthorizationUri(getUserAuthorizationUrl());
        resource.setClientId(getClientSettings().getClientId());
        resource.setScope(getClientSettings().getScopes());
        resource.setClientSecret(getClientSettings().getClientSecret());
        resource.setUseCurrentUri(true);

        return resource;
    }
 
Example #17
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 #18
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 #19
Source File: OAuth2ClientTokenSevices.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public void removeAccessToken(OAuth2ProtectedResourceDetails resource,
        Authentication authentication) {

    settings.setAccessToken(null);
    settings.setExpiresIn(null);
}
 
Example #20
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest request) throws UserRedirectRequiredException, OAuth2AccessDeniedException {
    MultiValueMap<String, String> form = new LinkedMultiValueMap();
    form.add("grant_type", "refresh_token");
    form.add("refresh_token", refreshToken.getValue());
    form.add("appid", resource.getClientId());

    try {
        return this.retrieveToken(request, resource, form, this.getHeadersForTokenRequest(request));
    } catch (OAuth2AccessDeniedException var6) {
        throw this.getRedirectForAuthorization((AuthorizationCodeResourceDetails)resource, request);
    }
}
 
Example #21
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 #22
Source File: OAuth2ClientTokenSevices.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public OAuth2AccessToken getAccessToken(OAuth2ProtectedResourceDetails resource, Authentication authentication) {
    ClientUser clientUser = getClientUser(authentication);

    String accessToken = clientUser.getAccessToken();
    Calendar expirationDate = clientUser.getAccessTokenValidity();

    if (accessToken == null) return null;

    DefaultOAuth2AccessToken oAuth2AccessToken = new DefaultOAuth2AccessToken(accessToken);
    oAuth2AccessToken.setExpiration(expirationDate.getTime());

    return oAuth2AccessToken;
}
 
Example #23
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
protected OAuth2AccessToken retrieveToken(final AccessTokenRequest request,
                                          OAuth2ProtectedResourceDetails resource,
                                          MultiValueMap<String, String> form,
                                          HttpHeaders headers) throws OAuth2AccessDeniedException {
    try {
        this.authenticationHandler.authenticateTokenRequest(resource, form, headers);
        this.tokenRequestEnhancer.enhance(request, resource, form, headers);
        final ResponseExtractor<OAuth2AccessToken> delegate = this.getResponseExtractor();

        ResponseExtractor<OAuth2AccessToken> extractor = new ResponseExtractor<OAuth2AccessToken>() {
            public OAuth2AccessToken extractData(ClientHttpResponse response) throws IOException {
                if(response.getHeaders().containsKey("Set-Cookie")) {
                    request.setCookie(response.getHeaders().getFirst("Set-Cookie"));
                }

                return (OAuth2AccessToken)delegate.extractData(response);
            }
        };
        System.out.println("URI == " + this.getAccessTokenUri(resource, form));
        return (OAuth2AccessToken)this.getRestTemplate().execute(this.getAccessTokenUri(resource, form),
                this.getHttpMethod(),
                this.getRequestCallback(resource, form, headers),
                extractor,
                form.toSingleValueMap());
    } catch (OAuth2Exception var8) {
        System.out.println(var8.toString());
        throw new OAuth2AccessDeniedException("Access token denied.", resource, var8);
    } catch (RestClientException var9) {
        System.out.println(var9.toString());
        throw new OAuth2AccessDeniedException("Error requesting access token.", resource, var9);
    }
}
 
Example #24
Source File: OAuth2ClientTokenSevices.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public void removeAccessToken(OAuth2ProtectedResourceDetails resource,
        Authentication authentication) {
    ClientUser clientUser = getClientUser(authentication);

    clientUser.setAccessToken(null);
    clientUser.setRefreshToken(null);
    clientUser.setAccessTokenValidity(null);

    users.save(clientUser);
}
 
Example #25
Source File: OAuth2ClientTokenSevices.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
@Override
public void saveAccessToken(OAuth2ProtectedResourceDetails resource,
        Authentication authentication, OAuth2AccessToken accessToken) {
    Calendar expirationDate = Calendar.getInstance();
    expirationDate.setTime(accessToken.getExpiration());

    ClientUser clientUser = getClientUser(authentication);

    clientUser.setAccessToken(accessToken.getValue());
    clientUser.setAccessTokenValidity(expirationDate);
    clientUser.setRefreshToken(accessToken.getRefreshToken().getValue());

    users.save(clientUser);
}
 
Example #26
Source File: OAuthClientConfiguration.java    From microservices-basics-spring-boot with Apache License 2.0 5 votes vote down vote up
private OAuth2ProtectedResourceDetails authServer() {
	ResourceOwnerPasswordResourceDetails resourceOwnerPasswordResourceDetails = new ResourceOwnerPasswordResourceDetails();
	// Need to set the access token URI since RestTemplate tries to access it first
	// time
	resourceOwnerPasswordResourceDetails.setAccessTokenUri("/userauth/oauth/token");
	return resourceOwnerPasswordResourceDetails;
}
 
Example #27
Source File: OAuth2ClientTokenSevices.java    From OAuth-2.0-Cookbook with 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);
}
 
Example #28
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 #29
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;
}
 
Example #30
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());
}