Example usage for org.springframework.security.oauth2.client.resource UserRedirectRequiredException getRedirectUri

List of usage examples for org.springframework.security.oauth2.client.resource UserRedirectRequiredException getRedirectUri

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.client.resource UserRedirectRequiredException getRedirectUri.

Prototype

public String getRedirectUri() 

Source Link

Document

The uri to which the user is to be redirected.

Usage

From source file:spring.AbstractAuthorizationCodeProviderTests.java

@Test
@OAuth2ContextConfiguration(resource = MyTrustedClient.class, initialize = false)
public void testUserDeniesConfirmation() throws Exception {
    approveAccessTokenGrant("http://anywhere", false);
    String location = null;/*from w ww  .j ava2 s  .  com*/
    try {
        assertNotNull(context.getAccessToken());
        fail("Expected UserRedirectRequiredException");
    } catch (UserRedirectRequiredException e) {
        location = e.getRedirectUri();
    }
    assertTrue("Wrong location: " + location, location.contains("state="));
    assertTrue(location.startsWith("http://anywhere"));
    assertTrue(location.substring(location.indexOf('?')).contains("error=access_denied"));
    // It was a redirect that triggered our client redirect exception:
    assertEquals(HttpStatus.FOUND, getTokenEndpointResponse().getStatusCode());
}

From source file:org.meruvian.yama.webapp.interceptor.OAuth2ClientContextInterceptor.java

/**
 * Redirect the user according to the specified exception.
 * //from   ww w. j  a  v  a  2 s . c o  m
 * @param resourceThatNeedsAuthorization
 * @param e The user redirect exception.
 * @param request The request.
 * @param response The response.
 */
protected void redirectUser(UserRedirectRequiredException e, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    String redirectUri = e.getRedirectUri();
    StringBuilder builder = new StringBuilder(redirectUri);
    Map<String, String> requestParams = e.getRequestParams();
    char appendChar = redirectUri.indexOf('?') < 0 ? '?' : '&';
    for (Map.Entry<String, String> param : requestParams.entrySet()) {
        try {
            builder.append(appendChar).append(param.getKey()).append('=')
                    .append(URLEncoder.encode(param.getValue(), "UTF-8"));
        } catch (UnsupportedEncodingException uee) {
            throw new IllegalStateException(uee);
        }
        appendChar = '&';
    }

    if (e.getStateKey() != null) {
        builder.append(appendChar).append("state").append('=').append(e.getStateKey());
    }

    this.redirectStrategy.sendRedirect(request, response, builder.toString());

}

From source file:org.openmhealth.shim.runkeeper.RunkeeperShim.java

@Override
protected String getAuthorizationUrl(UserRedirectRequiredException exception) {

    final OAuth2ProtectedResourceDetails resource = getResource();

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(exception.getRedirectUri())
            .queryParam("state", exception.getStateKey()).queryParam("client_id", resource.getClientId())
            .queryParam("response_type", "code").queryParam("redirect_uri", getCallbackUrl());

    return uriBuilder.build().encode().toUriString();
}

From source file:org.openmhealth.shim.misfit.MisfitShim.java

@Override
protected String getAuthorizationUrl(UserRedirectRequiredException exception) {

    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", getCallbackUrl());

    return uriBuilder.build().encode().toUriString();
}

From source file:org.openmhealth.shim.jawbone.JawboneShim.java

@Override
protected String getAuthorizationUrl(UserRedirectRequiredException exception) {

    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", getCallbackUrl());

    return uriBuilder.build().encode().toUriString();

}

From source file:org.openmhealth.shim.googlefit.GoogleFitShim.java

@Override
protected String getAuthorizationUrl(UserRedirectRequiredException exception) {
    final OAuth2ProtectedResourceDetails resource = getResource();

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(exception.getRedirectUri())
            .queryParam("state", exception.getStateKey()).queryParam("client_id", resource.getClientId())
            .queryParam("response_type", "code").queryParam("access_type", "offline")
            .queryParam("approval_prompt", "force")
            .queryParam("scope", StringUtils.collectionToDelimitedString(resource.getScope(), " "))
            .queryParam("redirect_uri", getCallbackUrl());

    return uriBuilder.build().encode().toUriString();
}

From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java

@Test
@OAuth2ContextConfiguration(resource = MyTrustedClient.class, initialize = false)
public void testUserDeniesConfirmation() throws Exception {
    approveAccessTokenGrant("http://anywhere", false);
    String location = null;/*from  w w w  .  j  a v  a 2s .c o m*/
    try {
        assertNotNull(context.getAccessToken());
        fail("Expected UserRedirectRequiredException");
    } catch (UserRedirectRequiredException e) {
        location = e.getRedirectUri();
    }
    assertTrue("Wrong location: " + location, location.contains("state="));
    assertTrue(location.startsWith("http://anywhere"));
    assertTrue(location.substring(location.indexOf('?')).contains("error=access_denied"));
    // It was a redirect that triggered our client redirect exception:
    assertEquals(HttpStatus.FOUND, tokenEndpointResponse.getStatusCode());
}

From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java

protected void approveAccessTokenGrant(String currentUri, boolean approved) {

    AccessTokenRequest request = context.getAccessTokenRequest();
    request.setHeaders(getAuthenticatedHeaders());
    AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails) context.getResource();

    if (currentUri != null) {
        request.setCurrentUri(currentUri);
    }//from   w w  w .ja va  2s. c  o m

    String location = null;

    try {
        // First try to obtain the access token...
        assertNotNull(context.getAccessToken());
        fail("Expected UserRedirectRequiredException");
    } catch (UserRedirectRequiredException e) {
        // Expected and necessary, so that the correct state is set up in the request...
        location = e.getRedirectUri();
    }

    assertTrue(location.startsWith(resource.getUserAuthorizationUri()));
    assertNull(request.getAuthorizationCode());

    verifyAuthorizationPage(context.getRestTemplate(), location);

    try {
        // Now try again and the token provider will redirect for user approval...
        assertNotNull(context.getAccessToken());
        fail("Expected UserRedirectRequiredException");
    } catch (UserApprovalRequiredException e) {
        // Expected and necessary, so that the user can approve the grant...
        location = e.getApprovalUri();
    }

    assertTrue(location.startsWith(resource.getUserAuthorizationUri()));
    assertNull(request.getAuthorizationCode());

    // The approval (will be processed on the next attempt to obtain an access token)...
    request.set(OAuth2Utils.USER_OAUTH_APPROVAL, "" + approved);

}

From source file:org.openmhealth.shim.ihealth.IHealthShim.java

@Override
protected String getAuthorizationUrl(UserRedirectRequiredException exception) {
    final OAuth2ProtectedResourceDetails resource = getResource();

    UriComponentsBuilder callBackUriBuilder = UriComponentsBuilder.fromUriString(getCallbackUrl())
            .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("redirect_uri", callBackUriBuilder.build().toString());

    return authorizationUriBuilder.build().encode().toString();
}

From source file:org.openmhealth.shim.OAuth2ShimBase.java

@Override
public AuthorizationRequestParameters getAuthorizationRequestParameters(String username,
        Map<String, String> addlParameters) throws ShimException {
    OAuth2RestOperations restTemplate = restTemplate();
    try {// www.j a  v  a  2 s.co  m
        trigger(restTemplate, getTriggerDataRequest());
        return AuthorizationRequestParameters.authorized();
    } catch (UserRedirectRequiredException e) {
        /**
         * If an exception was thrown it means a redirect is required
         * for user's external authorization with toolmaker.
         */
        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));
        authRequestParams.setSerializedRequest(SerializationUtils.serialize(accessTokenRequest));
        authRequestParams.setStateKey(stateKey);

        authorizationRequestParametersRepo.save(authRequestParams);
        return authRequestParams;
    }
}