Example usage for org.springframework.security.oauth2.provider AuthorizationRequest getState

List of usage examples for org.springframework.security.oauth2.provider AuthorizationRequest getState

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.provider AuthorizationRequest getState.

Prototype

public String getState() 

Source Link

Usage

From source file:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java

private String getSuccessfulRedirect(AuthorizationRequest authorizationRequest, String authorizationCode) {
    if (isNull(authorizationCode)) {
        throw new IllegalStateException("No authorization code found in the current request scope.");
    }/*from w  ww. j a  v  a 2 s. c om*/

    Map<String, String> query = new LinkedHashMap<>();
    query.put("code", authorizationCode);

    String state = authorizationRequest.getState();
    if (nonNull(state)) {
        query.put("state", state);
    }

    return append(authorizationRequest.getRedirectUri(), query, false);
}

From source file:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java

private String generateCode(AuthorizationRequest authorizationRequest) throws AuthenticationException {
    try {/* www  . j a va2  s. c  om*/
        OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(authorizationRequest);
        OAuth2Authentication combinedAuth = new OAuth2Authentication(storedOAuth2Request, null);
        return authorizationCodeServices.createAuthorizationCode(combinedAuth);
    } catch (OAuth2Exception e) {
        if (authorizationRequest.getState() != null) {
            e.addAdditionalInformation("state", authorizationRequest.getState());
        }
        throw e;
    }
}

From source file:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java

private String appendAccessToken(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken) {

    Map<String, Object> vars = new LinkedHashMap<>();
    Map<String, String> keys = new HashMap<>();

    if (isNull(accessToken)) {
        throw new InvalidRequestException("An implicit grant could not be made");
    }/*from  ww  w .j av  a 2 s  . co  m*/

    vars.put("access_token", accessToken.getValue());
    vars.put("token_type", accessToken.getTokenType());
    String state = authorizationRequest.getState();

    if (nonNull(state)) {
        vars.put("state", state);
    }

    Date expiration = accessToken.getExpiration();
    if (nonNull(expiration)) {
        long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000;
        vars.put("expires_in", expires_in);
    }

    String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
    if (isNull(originalScope)
            || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) {
        vars.put("scope", OAuth2Utils.formatParameterList(accessToken.getScope()));
    }

    Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
    for (String key : additionalInformation.keySet()) {
        Object value = additionalInformation.get(key);
        if (nonNull(value)) {
            keys.put("extra_" + key, key);
            vars.put("extra_" + key, value);
        }
    }
    // Do not include the refresh token (even if there is one)
    return append(authorizationRequest.getRedirectUri(), vars, keys, true);
}

From source file:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java

private String getUnsuccessfulRedirect(AuthorizationRequest authorizationRequest, OAuth2Exception failure,
        boolean fragment) {
    if (isNull(authorizationRequest) || isNull(authorizationRequest.getRedirectUri())) {
        // we have no redirect for the user. very sad.
        throw new UnapprovedClientAuthenticationException("Authorization failure, and no redirect URI.",
                failure);/*  w  ww .j a va 2  s .  c o m*/
    }

    Map<String, String> query = new LinkedHashMap<>();

    query.put("error", failure.getOAuth2ErrorCode());
    query.put("error_description", failure.getMessage());

    if (nonNull(authorizationRequest.getState())) {
        query.put("state", authorizationRequest.getState());
    }

    if (nonNull(failure.getAdditionalInformation())) {
        for (Map.Entry<String, String> additionalInfo : failure.getAdditionalInformation().entrySet()) {
            query.put(additionalInfo.getKey(), additionalInfo.getValue());
        }
    }

    return append(authorizationRequest.getRedirectUri(), query, fragment);
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

Map<String, Object> unmodifiableMap(AuthorizationRequest authorizationRequest) {
    Map<String, Object> authorizationRequestMap = new HashMap<>();

    authorizationRequestMap.put(OAuth2Utils.CLIENT_ID, authorizationRequest.getClientId());
    authorizationRequestMap.put(OAuth2Utils.STATE, authorizationRequest.getState());
    authorizationRequestMap.put(OAuth2Utils.REDIRECT_URI, authorizationRequest.getRedirectUri());

    if (authorizationRequest.getResponseTypes() != null) {
        authorizationRequestMap.put(OAuth2Utils.RESPONSE_TYPE,
                Collections.unmodifiableSet(new HashSet<>(authorizationRequest.getResponseTypes())));
    }//from w  ww.j av a 2  s.  c  o m
    if (authorizationRequest.getScope() != null) {
        authorizationRequestMap.put(OAuth2Utils.SCOPE,
                Collections.unmodifiableSet(new HashSet<>(authorizationRequest.getScope())));
    }

    authorizationRequestMap.put("approved", authorizationRequest.isApproved());

    if (authorizationRequest.getResourceIds() != null) {
        authorizationRequestMap.put("resourceIds",
                Collections.unmodifiableSet(new HashSet<>(authorizationRequest.getResourceIds())));
    }
    if (authorizationRequest.getAuthorities() != null) {
        authorizationRequestMap.put("authorities", Collections
                .unmodifiableSet(new HashSet<GrantedAuthority>(authorizationRequest.getAuthorities())));
    }

    return authorizationRequestMap;
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

private boolean isAuthorizationRequestModified(AuthorizationRequest authorizationRequest,
        Map<String, Object> originalAuthorizationRequest) {
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getClientId(),
            originalAuthorizationRequest.get(OAuth2Utils.CLIENT_ID))) {
        return true;
    }/*from  ww  w  . j ava2s .  com*/
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getState(),
            originalAuthorizationRequest.get(OAuth2Utils.STATE))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getRedirectUri(),
            originalAuthorizationRequest.get(OAuth2Utils.REDIRECT_URI))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getResponseTypes(),
            originalAuthorizationRequest.get(OAuth2Utils.RESPONSE_TYPE))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.isApproved(),
            originalAuthorizationRequest.get("approved"))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getResourceIds(),
            originalAuthorizationRequest.get("resourceIds"))) {
        return true;
    }
    if (!ObjectUtils.nullSafeEquals(authorizationRequest.getAuthorities(),
            originalAuthorizationRequest.get("authorities"))) {
        return true;
    }

    return !ObjectUtils.nullSafeEquals(authorizationRequest.getScope(),
            originalAuthorizationRequest.get(OAuth2Utils.SCOPE));
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

private String getSuccessfulRedirect(AuthorizationRequest authorizationRequest, String authorizationCode) {

    if (authorizationCode == null) {
        throw new IllegalStateException("No authorization code found in the current request scope.");
    }//from   w ww. j  a  va2 s  . c  om

    UriComponentsBuilder template = UriComponentsBuilder.fromUriString(authorizationRequest.getRedirectUri());
    template.queryParam("code", encode(authorizationCode));

    String state = authorizationRequest.getState();
    if (state != null) {
        template.queryParam("state", encode(state));
    }

    return template.build(true).toUriString();
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

private String generateCode(AuthorizationRequest authorizationRequest, Authentication authentication)
        throws AuthenticationException {

    try {//from   w w w  .j a va  2  s  . co  m

        OAuth2Request storedOAuth2Request = getOAuth2RequestFactory().createOAuth2Request(authorizationRequest);

        OAuth2Authentication combinedAuth = new OAuth2Authentication(storedOAuth2Request, authentication);
        String code = authorizationCodeServices.createAuthorizationCode(combinedAuth);

        return code;

    } catch (OAuth2Exception e) {

        if (authorizationRequest.getState() != null) {
            e.addAdditionalInformation("state", authorizationRequest.getState());
        }

        throw e;

    }
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java

private String getUnsuccessfulRedirect(AuthorizationRequest authorizationRequest, OAuth2Exception failure,
        boolean fragment) {

    if (authorizationRequest == null || authorizationRequest.getRedirectUri() == null) {
        // we have no redirect for the user. very sad.
        throw new UnapprovedClientAuthenticationException("Authorization failure, and no redirect URI.",
                failure);/*from  ww  w  . j  a  v  a 2 s  .c o  m*/
    }

    UriComponentsBuilder template = UriComponentsBuilder.fromUriString(authorizationRequest.getRedirectUri());
    StringBuilder values = new StringBuilder();

    values.append("error=" + encode(failure.getOAuth2ErrorCode()));
    values.append("&error_description=" + encode(failure.getMessage()));

    if (authorizationRequest.getState() != null) {
        values.append("&state=" + encode(authorizationRequest.getState()));
    }

    if (failure.getAdditionalInformation() != null) {
        for (Map.Entry<String, String> additionalInfo : failure.getAdditionalInformation().entrySet()) {
            values.append("&" + encode(additionalInfo.getKey()) + "=" + encode(additionalInfo.getValue()));
        }
    }

    if (fragment) {
        template.fragment(values.toString());
    } else {
        template.query(values.toString());
    }

    return template.build(true).toUriString();

}

From source file:org.mitre.oauth2.web.OAuthConfirmationController.java

@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping("/oauth/confirm_access")
public String confimAccess(Map<String, Object> model,
        @ModelAttribute("authorizationRequest") AuthorizationRequest authRequest, Principal p) {

    // Check the "prompt" parameter to see if we need to do special processing

    String prompt = (String) authRequest.getExtensions().get(PROMPT);
    List<String> prompts = Splitter.on(PROMPT_SEPARATOR).splitToList(Strings.nullToEmpty(prompt));
    ClientDetailsEntity client = null;/*from w ww .java 2 s . c  om*/

    try {
        client = clientService.loadClientByClientId(authRequest.getClientId());
    } catch (OAuth2Exception e) {
        logger.error("confirmAccess: OAuth2Exception was thrown when attempting to load client", e);
        model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
        return HttpCodeView.VIEWNAME;
    } catch (IllegalArgumentException e) {
        logger.error("confirmAccess: IllegalArgumentException was thrown when attempting to load client", e);
        model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
        return HttpCodeView.VIEWNAME;
    }

    if (client == null) {
        logger.error("confirmAccess: could not find client " + authRequest.getClientId());
        model.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
        return HttpCodeView.VIEWNAME;
    }

    if (prompts.contains("none")) {
        // if we've got a redirect URI then we'll send it

        String url = redirectResolver.resolveRedirect(authRequest.getRedirectUri(), client);

        try {
            URIBuilder uriBuilder = new URIBuilder(url);

            uriBuilder.addParameter("error", "interaction_required");
            if (!Strings.isNullOrEmpty(authRequest.getState())) {
                uriBuilder.addParameter("state", authRequest.getState()); // copy the state parameter if one was given
            }

            return "redirect:" + uriBuilder.toString();

        } catch (URISyntaxException e) {
            logger.error("Can't build redirect URI for prompt=none, sending error instead", e);
            model.put("code", HttpStatus.FORBIDDEN);
            return HttpCodeView.VIEWNAME;
        }
    }

    model.put("auth_request", authRequest);
    model.put("client", client);

    String redirect_uri = authRequest.getRedirectUri();

    model.put("redirect_uri", redirect_uri);

    // pre-process the scopes
    Set<SystemScope> scopes = scopeService.fromStrings(authRequest.getScope());

    Set<SystemScope> sortedScopes = new LinkedHashSet<>(scopes.size());
    Set<SystemScope> systemScopes = scopeService.getAll();

    // sort scopes for display based on the inherent order of system scopes
    for (SystemScope s : systemScopes) {
        if (scopes.contains(s)) {
            sortedScopes.add(s);
        }
    }

    // add in any scopes that aren't system scopes to the end of the list
    sortedScopes.addAll(Sets.difference(scopes, systemScopes));

    model.put("scopes", sortedScopes);

    // get the userinfo claims for each scope
    UserInfo user = userInfoService.getByUsername(p.getName());
    Map<String, Map<String, String>> claimsForScopes = new HashMap<>();
    if (user != null) {
        JsonObject userJson = user.toJson();

        for (SystemScope systemScope : sortedScopes) {
            Map<String, String> claimValues = new HashMap<>();

            Set<String> claims = scopeClaimTranslationService.getClaimsForScope(systemScope.getValue());
            for (String claim : claims) {
                if (userJson.has(claim) && userJson.get(claim).isJsonPrimitive()) {
                    // TODO: this skips the address claim
                    claimValues.put(claim, userJson.get(claim).getAsString());
                }
            }

            claimsForScopes.put(systemScope.getValue(), claimValues);
        }
    }

    model.put("claims", claimsForScopes);

    // client stats
    Integer count = statsService.getCountForClientId(client.getId());
    model.put("count", count);

    // contacts
    if (client.getContacts() != null) {
        String contacts = Joiner.on(", ").join(client.getContacts());
        model.put("contacts", contacts);
    }

    // if the client is over a week old and has more than one registration, don't give such a big warning
    // instead, tag as "Generally Recognized As Safe" (gras)
    Date lastWeek = new Date(System.currentTimeMillis() - (60 * 60 * 24 * 7 * 1000));
    if (count > 1 && client.getCreatedAt() != null && client.getCreatedAt().before(lastWeek)) {
        model.put("gras", true);
    } else {
        model.put("gras", false);
    }

    return "approve";
}