Example usage for org.springframework.security.oauth2.client.token AccessTokenRequest getPreservedState

List of usage examples for org.springframework.security.oauth2.client.token AccessTokenRequest getPreservedState

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.client.token AccessTokenRequest getPreservedState.

Prototype

Object getPreservedState();

Source Link

Usage

From source file:com.zhm.config.MyAuthorizationCodeAccessTokenProvider.java

private MultiValueMap<String, String> getParametersForTokenRequest(AuthorizationCodeResourceDetails resource,
        AccessTokenRequest request) {

    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.set("grant_type", "authorization_code");
    form.set("code", request.getAuthorizationCode());

    Object preservedState = request.getPreservedState();
    if (request.getStateKey() != null || stateMandatory) {
        // The token endpoint has no use for the state so we don't send it back, but we are using it
        // for CSRF detection client side...
        if (preservedState == null) {
            throw new InvalidRequestException(
                    "Possible CSRF detected - state parameter was required but no state could be found");
        }//from   w  w  w .ja v a2 s .c o m
    }

    // Extracting the redirect URI from a saved request should ignore the current URI, so it's not simply a call to
    // resource.getRedirectUri()
    String redirectUri = null;
    // Get the redirect uri from the stored state
    if (preservedState instanceof String) {
        // Use the preserved state in preference if it is there
        // TODO: treat redirect URI as a special kind of state (this is a historical mini hack)
        redirectUri = String.valueOf(preservedState);
    } else {
        redirectUri = resource.getRedirectUri(request);
    }

    if (redirectUri != null && !"NONE".equals(redirectUri)) {
        form.set("redirect_uri", redirectUri);
    }

    return form;

}

From source file:com.emergya.spring.security.oauth.google.GoogleAuthorizationCodeAccessTokenProvider.java

private MultiValueMap<String, String> getParametersForTokenRequest(
        final AuthorizationCodeResourceDetails resource, final AccessTokenRequest request) {

    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.set("grant_type", "authorization_code");
    form.set("code", request.getAuthorizationCode());

    Object preservedState = request.getPreservedState();
    if (request.getStateKey() != null) {
        // The token endpoint has no use for the state so we don't send it back, but we are using it
        // for CSRF detection client side...
        if (preservedState == null) {
            throw new InvalidRequestException(
                    "Possible CSRF detected - state parameter was present but no state could be found");
        }//from   w ww .ja  v a2s .  co m
    }

    // Extracting the redirect URI from a saved request should ignore the current URI, so it's not simply a call to
    // resource.getRedirectUri()
    String redirectUri;
    // Get the redirect uri from the stored state
    if (preservedState instanceof String) {
        // Use the preserved state in preference if it is there
        // TODO: treat redirect URI as a special kind of state (this is a historical mini hack)
        redirectUri = String.valueOf(preservedState);
    } else {
        redirectUri = resource.getRedirectUri(request);
    }

    if (redirectUri != null && !"NONE".equals(redirectUri)) {
        form.set("redirect_uri", redirectUri);
    }

    return form;

}

From source file:com.zhm.config.MyAuthorizationCodeAccessTokenProvider.java

private MultiValueMap<String, String> getParametersForAuthorizeRequest(
        AuthorizationCodeResourceDetails resource, AccessTokenRequest request) {

    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.set("response_type", "code");
    form.set("client_id", resource.getClientId());

    if (request.get("scope") != null) {
        form.set("scope", request.getFirst("scope"));
    } else {//w w w  .j  a  va  2s . co m
        form.set("scope", OAuth2Utils.formatParameterList(resource.getScope()));
    }

    // Extracting the redirect URI from a saved request should ignore the current URI, so it's not simply a call to
    // resource.getRedirectUri()
    String redirectUri = resource.getPreEstablishedRedirectUri();

    Object preservedState = request.getPreservedState();
    if (redirectUri == null && preservedState != null) {
        // no pre-established redirect uri: use the preserved state
        // TODO: treat redirect URI as a special kind of state (this is a historical mini hack)
        redirectUri = String.valueOf(preservedState);
    } else {
        redirectUri = request.getCurrentUri();
    }

    String stateKey = request.getStateKey();
    if (stateKey != null) {
        form.set("state", stateKey);
        if (preservedState == null) {
            throw new InvalidRequestException(
                    "Possible CSRF detected - state parameter was present but no state could be found");
        }
    }

    if (redirectUri != null) {
        form.set("redirect_uri", redirectUri);
    }

    return form;

}

From source file:com.emergya.spring.security.oauth.google.GoogleAuthorizationCodeAccessTokenProvider.java

private MultiValueMap<String, String> getParametersForAuthorizeRequest(GoogleAuthCodeResourceDetails resource,
        AccessTokenRequest request) {

    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.set("response_type", "code");
    form.set("client_id", resource.getClientId());

    if (request.get("scope") != null) {
        form.set("scope", request.getFirst("scope"));
    } else {// w  w  w .j  ava2s.co  m
        form.set("scope", OAuth2Utils.formatParameterList(resource.getScope()));
    }

    // Extracting the redirect URI from a saved request should ignore the current URI, so it's not simply a call to
    // resource.getRedirectUri()
    String redirectUri = resource.getPreEstablishedRedirectUri();

    Object preservedState = request.getPreservedState();
    if (redirectUri == null && preservedState != null) {
        // no pre-established redirect uri: use the preserved state
        // TODO: treat redirect URI as a special kind of state (this is a historical mini hack)
        redirectUri = String.valueOf(preservedState);
    } else {
        redirectUri = request.getCurrentUri();
    }

    String stateKey = request.getStateKey();
    if (stateKey != null) {
        form.set("state", stateKey);
        if (preservedState == null) {
            throw new InvalidRequestException(
                    "Possible CSRF detected - state parameter was present but no state could be found");
        }
    }

    form.set("approval_prompt", resource.getApprovalPrompt());

    if (StringUtils.isEmpty(resource.getLoginHint())) {
        form.set("login_hint", resource.getLoginHint());
    }

    if (redirectUri != null) {
        form.set("redirect_uri", redirectUri);
    }

    return form;

}

From source file:com.emergya.spring.security.oauth.google.GoogleAuthorizationCodeAccessTokenProvider.java

/**
 * Obtains the authorization code from the access token request.
 *
 * @param details the authenticatoin details
 * @param request the access token request
 * @return the authorization code//ww w  .ja  v a  2s  . c o m
 * @throws UserRedirectRequiredException when redirection is required
 * @throws UserApprovalRequiredException when the user requires approval
 * @throws AccessDeniedException when the user is denied access
 * @throws OAuth2AccessDeniedException when the user is denied access but we dont want the default Spring Security handling
 */
public final String obtainAuthorizationCode(final OAuth2ProtectedResourceDetails details,
        final AccessTokenRequest request) throws UserRedirectRequiredException, UserApprovalRequiredException,
        AccessDeniedException, OAuth2AccessDeniedException {

    GoogleAuthCodeResourceDetails resource;

    try {
        resource = (GoogleAuthCodeResourceDetails) details;
    } catch (ClassCastException ex) {
        throw new IllegalArgumentException("details is not an instance of class GoogleAuthCodeResourceDetails");
    }

    HttpHeaders headers = getHeadersForAuthorizationRequest(request);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    if (request.containsKey(OAuth2Utils.USER_OAUTH_APPROVAL)) {
        form.set(OAuth2Utils.USER_OAUTH_APPROVAL, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL));
        for (String scope : details.getScope()) {
            form.set(scopePrefix + scope, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL));
        }
    } else {
        form.putAll(getParametersForAuthorizeRequest(resource, request));
    }
    authorizationRequestEnhancer.enhance(request, resource, form, headers);
    final AccessTokenRequest copy = request;

    final ResponseExtractor<ResponseEntity<Void>> delegate = getAuthorizationResponseExtractor();
    ResponseExtractor<ResponseEntity<Void>> extractor = new CookieResponseExtractor(copy, delegate);
    // Instead of using restTemplate.exchange we use an explicit response extractor here so it can be overridden by
    // subclasses
    ResponseEntity<Void> response = getRestTemplate().execute(resource.getUserAuthorizationUri(),
            HttpMethod.POST, getRequestCallback(resource, form, headers), extractor, form.toSingleValueMap());

    if (response.getStatusCode() == HttpStatus.OK) {
        // Need to re-submit with approval...
        throw getUserApprovalSignal(resource, request);
    }

    URI location = response.getHeaders().getLocation();
    String query = location.getQuery();
    Map<String, String> map = OAuth2Utils.extractMap(query);
    if (map.containsKey("state")) {
        request.setStateKey(map.get("state"));
        if (request.getPreservedState() == null) {
            String redirectUri = resource.getRedirectUri(request);
            if (redirectUri != null) {
                request.setPreservedState(redirectUri);
            } else {
                request.setPreservedState(new Object());
            }
        }
    }

    String code = map.get("code");
    if (code == null) {
        throw new UserRedirectRequiredException(location.toString(), form.toSingleValueMap());
    }
    request.set("code", code);
    return code;

}

From source file:com.zhm.config.MyAuthorizationCodeAccessTokenProvider.java

public String obtainAuthorizationCode(OAuth2ProtectedResourceDetails details, AccessTokenRequest request)
        throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException,
        OAuth2AccessDeniedException {

    AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails) details;

    HttpHeaders headers = getHeadersForAuthorizationRequest(request);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    if (request.containsKey(OAuth2Utils.USER_OAUTH_APPROVAL)) {
        form.set(OAuth2Utils.USER_OAUTH_APPROVAL, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL));
        for (String scope : details.getScope()) {
            form.set(scopePrefix + scope, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL));
        }//from  w  w  w. ja va2  s .  c o m
    } else {
        form.putAll(getParametersForAuthorizeRequest(resource, request));
    }
    authorizationRequestEnhancer.enhance(request, resource, form, headers);
    final AccessTokenRequest copy = request;

    final ResponseExtractor<ResponseEntity<Void>> delegate = getAuthorizationResponseExtractor();
    ResponseExtractor<ResponseEntity<Void>> extractor = new ResponseExtractor<ResponseEntity<Void>>() {
        @Override
        public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException {
            if (response.getHeaders().containsKey("Set-Cookie")) {
                copy.setCookie(response.getHeaders().getFirst("Set-Cookie"));
            }
            return delegate.extractData(response);
        }
    };
    // Instead of using restTemplate.exchange we use an explicit response extractor here so it can be overridden by
    // subclasses
    ResponseEntity<Void> response = getRestTemplate().execute(resource.getUserAuthorizationUri(),
            HttpMethod.POST, getRequestCallback(resource, form, headers), extractor, form.toSingleValueMap());

    if (response.getStatusCode() == HttpStatus.OK) {
        // Need to re-submit with approval...
        throw getUserApprovalSignal(resource, request);
    }

    URI location = response.getHeaders().getLocation();
    String query = location.getQuery();
    Map<String, String> map = OAuth2Utils.extractMap(query);
    if (map.containsKey("state")) {
        request.setStateKey(map.get("state"));
        if (request.getPreservedState() == null) {
            String redirectUri = resource.getRedirectUri(request);
            if (redirectUri != null) {
                request.setPreservedState(redirectUri);
            } else {
                request.setPreservedState(new Object());
            }
        }
    }

    String code = map.get("code");
    if (code == null) {
        throw new UserRedirectRequiredException(location.toString(), form.toSingleValueMap());
    }
    request.set("code", code);
    return code;

}