Example usage for org.springframework.security.oauth2.common.util OAuth2Utils REDIRECT_URI

List of usage examples for org.springframework.security.oauth2.common.util OAuth2Utils REDIRECT_URI

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common.util OAuth2Utils REDIRECT_URI.

Prototype

String REDIRECT_URI

To view the source code for org.springframework.security.oauth2.common.util OAuth2Utils REDIRECT_URI.

Click Source Link

Document

Constant to use while parsing and formatting parameter maps for OAuth2 requests

Usage

From source file:org.mitre.openid.connect.ConnectOAuth2RequestFactory.java

@Override
public AuthorizationRequest createAuthorizationRequest(Map<String, String> inputParams) {

    AuthorizationRequest request = new AuthorizationRequest(inputParams, Collections.<String, String>emptyMap(),
            inputParams.get(OAuth2Utils.CLIENT_ID),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.SCOPE)), null, null, false,
            inputParams.get(OAuth2Utils.STATE), inputParams.get(OAuth2Utils.REDIRECT_URI),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.RESPONSE_TYPE)));

    //Add extension parameters to the 'extensions' map

    if (inputParams.containsKey("prompt")) {
        request.getExtensions().put("prompt", inputParams.get("prompt"));
    }// w  w  w .ja va  2s  . c  om
    if (inputParams.containsKey("nonce")) {
        request.getExtensions().put("nonce", inputParams.get("nonce"));
    }

    if (inputParams.containsKey("claims")) {
        JsonObject claimsRequest = parseClaimRequest(inputParams.get("claims"));
        if (claimsRequest != null) {
            request.getExtensions().put("claims", claimsRequest.toString());
        }
    }

    if (inputParams.containsKey("request")) {
        request.getExtensions().put("request", inputParams.get("request"));
        processRequestObject(inputParams.get("request"), request);
    }

    if ((request.getScope() == null || request.getScope().isEmpty())) {
        if (request.getClientId() != null) {
            ClientDetails client = clientDetailsService.loadClientByClientId(request.getClientId());
            Set<String> clientScopes = client.getScope();
            request.setScope(clientScopes);
        }
    }

    return request;
}

From source file:org.mitre.openid.connect.request.ConnectOAuth2RequestFactory.java

@Override
public AuthorizationRequest createAuthorizationRequest(Map<String, String> inputParams) {

    AuthorizationRequest request = new AuthorizationRequest(inputParams, Collections.<String, String>emptyMap(),
            inputParams.get(OAuth2Utils.CLIENT_ID),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.SCOPE)), null, null, false,
            inputParams.get(OAuth2Utils.STATE), inputParams.get(OAuth2Utils.REDIRECT_URI),
            OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.RESPONSE_TYPE)));

    //Add extension parameters to the 'extensions' map

    if (inputParams.containsKey(PROMPT)) {
        request.getExtensions().put(PROMPT, inputParams.get(PROMPT));
    }/*w ww  .  ja v  a 2 s .  c  o m*/
    if (inputParams.containsKey(NONCE)) {
        request.getExtensions().put(NONCE, inputParams.get(NONCE));
    }

    if (inputParams.containsKey(CLAIMS)) {
        JsonObject claimsRequest = parseClaimRequest(inputParams.get(CLAIMS));
        if (claimsRequest != null) {
            request.getExtensions().put(CLAIMS, claimsRequest.toString());
        }
    }

    if (inputParams.containsKey(MAX_AGE)) {
        request.getExtensions().put(MAX_AGE, inputParams.get(MAX_AGE));
    }

    if (inputParams.containsKey(LOGIN_HINT)) {
        request.getExtensions().put(LOGIN_HINT, inputParams.get(LOGIN_HINT));
    }

    if (inputParams.containsKey(AUD)) {
        request.getExtensions().put(AUD, inputParams.get(AUD));
    }

    if (inputParams.containsKey(REQUEST)) {
        request.getExtensions().put(REQUEST, inputParams.get(REQUEST));
        processRequestObject(inputParams.get(REQUEST), request);
    }

    if (request.getClientId() != null) {
        try {
            ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId());

            if ((request.getScope() == null || request.getScope().isEmpty())) {
                Set<String> clientScopes = client.getScope();
                request.setScope(clientScopes);
            }

            if (request.getExtensions().get(MAX_AGE) == null && client.getDefaultMaxAge() != null) {
                request.getExtensions().put(MAX_AGE, client.getDefaultMaxAge().toString());
            }
        } catch (OAuth2Exception e) {
            logger.error("Caught OAuth2 exception trying to test client scopes and max age:", e);
        }
    }

    return request;
}

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

@Override
protected void configure() {
    setControllerPath("oauth");

    get("authorize", (req, resp) -> {
        Map<String, String> parameters = MapUtils.createOneDimMap(req.getQueryParams());
        AuthorizationRequest authorizationRequest = requestFactory.createAuthorizationRequest(parameters);

        Set<String> responseTypes = authorizationRequest.getResponseTypes();
        if (!responseTypes.contains("token") && !responseTypes.contains("code")) {
            throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
        }/*from  ww w. j a  v a  2 s.c o  m*/

        if (isNull(authorizationRequest.getClientId())) {
            throw new InvalidClientException("A client id must be provided");
        }

        ClientDetails client = clientDetailsService.loadClientByClientId(authorizationRequest.getClientId());

        String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
        String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
        if (isEmpty(resolvedRedirect)) {
            throw new RedirectMismatchException(
                    "A redirectUri must be either supplied or preconfigured in the ClientDetails");
        }
        authorizationRequest.setRedirectUri(resolvedRedirect);

        requestValidator.validateScope(authorizationRequest, client);

        authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest, null);
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, null);
        authorizationRequest.setApproved(approved);

        if (authorizationRequest.isApproved()) {
            if (responseTypes.contains("token")) {
                resp.status(HttpStatus.FOUND);
                resp.header(HeaderName.LOCATION, getImplicitGrantResponse(authorizationRequest));
            }
            if (responseTypes.contains("code")) {
                resp.status(HttpStatus.FOUND);
                resp.header(HeaderName.LOCATION, getAuthorizationCodeResponse(authorizationRequest));
            }
        }
    });
}

From source file:com.orcid.api.common.server.delegator.impl.OrcidClientCredentialEndPointDelegatorImpl.java

protected OAuth2AccessToken generateToken(Authentication client, Set<String> scopes, String code,
        String redirectUri, String grantType, String refreshToken, String state) {
    String clientId = client.getName();
    Map<String, String> authorizationParameters = new HashMap<String, String>();

    if (scopes != null) {
        String scopesString = StringUtils.join(scopes, ' ');
        authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
    }/*from  w w  w .  j  a v  a  2  s  .c o m*/

    authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
    if (code != null) {
        authorizationParameters.put("code", code);
        OrcidOauth2AuthoriziationCodeDetail authorizationCodeEntity = orcidOauth2AuthoriziationCodeDetailDao
                .find(code);

        if (authorizationCodeEntity != null) {
            if (orcidOauth2AuthoriziationCodeDetailDao.isPersistentToken(code)) {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "true");
            } else {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
            }

            if (!authorizationParameters.containsKey(OAuth2Utils.SCOPE)
                    || PojoUtil.isEmpty(authorizationParameters.get(OAuth2Utils.SCOPE))) {
                String scopesString = StringUtils.join(authorizationCodeEntity.getScopes(), ' ');
                authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
            }
        } else {
            authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
        }
    }
    if (redirectUri != null) {
        authorizationParameters.put(OAuth2Utils.REDIRECT_URI, redirectUri);
    }
    AuthorizationRequest authorizationRequest = getOAuth2RequestFactory()
            .createAuthorizationRequest(authorizationParameters);

    TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, grantType);

    OAuth2AccessToken token = getTokenGranter().grant(grantType, tokenRequest);
    Object params[] = { grantType };
    if (token == null) {
        LOGGER.info(
                "Unsupported grant type for OAuth2: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}",
                new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri });
        throw new UnsupportedGrantTypeException(
                localeManager.resolveMessage("apiError.unsupported_client_type.exception", params));
    }
    LOGGER.info(
            "OAuth2 access token granted: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}, token={}",
            new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri, token });

    return token;
}

From source file:org.cloudfoundry.identity.client.UaaContextFactory.java

protected UaaContext fetchTokenFromCode(final TokenRequest request) {
    String clientBasicAuth = getClientBasicAuthHeader(request);

    RestTemplate template = new RestTemplate();
    if (request.isSkipSslValidation()) {
        template.setRequestFactory(getNoValidatingClientHttpRequestFactory());
    }//from  w w  w.j a  va 2  s .  co  m
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.AUTHORIZATION, clientBasicAuth);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add(OAuth2Utils.GRANT_TYPE, "authorization_code");
    form.add(OAuth2Utils.REDIRECT_URI, request.getRedirectUri().toString());
    String responseType = "token";
    if (request.wantsIdToken()) {
        responseType += " id_token";
    }
    form.add(OAuth2Utils.RESPONSE_TYPE, responseType);
    form.add("code", request.getAuthorizationCode());

    ResponseEntity<CompositeAccessToken> token = template.exchange(request.getTokenEndpoint(), HttpMethod.POST,
            new HttpEntity<>(form, headers), CompositeAccessToken.class);
    return new UaaContextImpl(request, null, token.getBody());
}

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

@RequestMapping(value = "/oauth/authorize")
public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters,
        SessionStatus sessionStatus, Principal principal, HttpServletRequest request) {

    ClientDetails client;/*from  w ww  .j a v a 2s . co m*/
    String clientId;
    try {
        clientId = parameters.get("client_id");
        client = getClientServiceExtention().loadClientByClientId(clientId, IdentityZoneHolder.get().getId());
    } catch (NoSuchClientException x) {
        throw new InvalidClientException(x.getMessage());
    }

    // Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should
    // query off of the authorization request instead of referring back to the parameters map. The contents of the
    // parameters map will be stored without change in the AuthorizationRequest object once it is created.
    AuthorizationRequest authorizationRequest;
    try {
        authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters);
    } catch (DisallowedIdpException x) {
        return switchIdp(model, client, clientId, request);
    }

    Set<String> responseTypes = authorizationRequest.getResponseTypes();
    String grantType = deriveGrantTypeFromResponseType(responseTypes);

    if (!supported_response_types.containsAll(responseTypes)) {
        throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
    }

    if (authorizationRequest.getClientId() == null) {
        throw new InvalidClientException("A client id must be provided");
    }

    String resolvedRedirect = "";
    try {
        String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
        try {
            resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
        } catch (RedirectMismatchException rme) {
            throw new RedirectMismatchException(
                    "Invalid redirect " + redirectUriParameter + " did not match one of the registered values");
        }
        if (!StringUtils.hasText(resolvedRedirect)) {
            throw new RedirectMismatchException(
                    "A redirectUri must be either supplied or preconfigured in the ClientDetails");
        }

        boolean isAuthenticated = (principal instanceof Authentication)
                && ((Authentication) principal).isAuthenticated();

        if (!isAuthenticated) {
            throw new InsufficientAuthenticationException(
                    "User must be authenticated with Spring Security before authorization can be completed.");
        }

        if (!(responseTypes.size() > 0)) {
            return new ModelAndView(new RedirectView(
                    addQueryParameter(addQueryParameter(resolvedRedirect, "error", "invalid_request"),
                            "error_description", "Missing response_type in authorization request")));
        }

        authorizationRequest.setRedirectUri(resolvedRedirect);
        // We intentionally only validate the parameters requested by the client (ignoring any data that may have
        // been added to the request by the manager).
        oauth2RequestValidator.validateScope(authorizationRequest, client);

        // Some systems may allow for approval decisions to be remembered or approved by default. Check for
        // such logic here, and set the approved flag on the authorization request accordingly.
        authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest,
                (Authentication) principal);
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
        authorizationRequest.setApproved(approved);

        // Validation is all done, so we can check for auto approval...
        if (authorizationRequest.isApproved()) {
            if (responseTypes.contains("token") || responseTypes.contains("id_token")) {
                return getImplicitGrantOrHybridResponse(authorizationRequest, (Authentication) principal,
                        grantType);
            }
            if (responseTypes.contains("code")) {
                return new ModelAndView(
                        getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal));
            }
        }

        if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) {
            return new ModelAndView(
                    new RedirectView(addFragmentComponent(resolvedRedirect, "error=interaction_required")));
        } else {
            // Place auth request into the model so that it is stored in the session
            // for approveOrDeny to use. That way we make sure that auth request comes from the session,
            // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session.
            model.put(AUTHORIZATION_REQUEST, authorizationRequest);
            model.put("original_uri", UrlUtils.buildFullRequestUrl(request));
            model.put(ORIGINAL_AUTHORIZATION_REQUEST, unmodifiableMap(authorizationRequest));

            return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal);
        }
    } catch (RedirectMismatchException e) {
        sessionStatus.setComplete();
        throw e;
    } catch (Exception e) {
        sessionStatus.setComplete();
        logger.debug("Unable to handle /oauth/authorize, internal error", e);
        if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) {
            return new ModelAndView(
                    new RedirectView(addFragmentComponent(resolvedRedirect, "error=internal_server_error")));
        }

        throw e;
    }

}

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

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    String clientId = request.getParameter(OAuth2Utils.CLIENT_ID);
    String redirectUri = request.getParameter(OAuth2Utils.REDIRECT_URI);
    String[] responseTypes = ofNullable(request.getParameter(OAuth2Utils.RESPONSE_TYPE))
            .map(rt -> rt.split(" ")).orElse(new String[0]);

    ClientDetails client;//  w  w  w .j  a  v a 2 s  . c o  m
    try {
        client = getClientServiceExtention().loadClientByClientId(clientId, IdentityZoneHolder.get().getId());
    } catch (ClientRegistrationException e) {
        logger.debug("[prompt=none] Unable to look up client for client_id=" + clientId, e);
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return;
    }

    Set<String> redirectUris = ofNullable(client.getRegisteredRedirectUri()).orElse(EMPTY_SET);

    //if the client doesn't have a redirect uri set, the parameter is required.
    if (redirectUris.size() == 0 && !hasText(redirectUri)) {
        logger.debug("[prompt=none] Missing redirect_uri");
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return;
    }

    String resolvedRedirect;
    try {
        resolvedRedirect = redirectResolver.resolveRedirect(redirectUri, client);
    } catch (RedirectMismatchException rme) {
        logger.debug("[prompt=none] Invalid redirect " + redirectUri
                + " did not match one of the registered values");
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return;
    }

    HttpHost httpHost = URIUtils.extractHost(URI.create(resolvedRedirect));
    String sessionState = openIdSessionStateCalculator.calculate("", clientId, httpHost.toURI());
    boolean implicit = stream(responseTypes).noneMatch("code"::equalsIgnoreCase);
    String redirectLocation;
    String errorCode = authException instanceof InteractionRequiredException ? "interaction_required"
            : "login_required";
    if (implicit) {
        redirectLocation = addFragmentComponent(resolvedRedirect, "error=" + errorCode);
        redirectLocation = addFragmentComponent(redirectLocation, "session_state=" + sessionState);
    } else {
        redirectLocation = addQueryParameter(resolvedRedirect, "error", errorCode);
        redirectLocation = addQueryParameter(redirectLocation, "session_state", sessionState);
    }

    response.sendRedirect(redirectLocation);
}

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   ww  w.  j  a v a 2s .  c  om
    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;
    }//  www  . j a  va 2 s .  c  om
    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 ModelAndView handleException(Exception e, ServletWebRequest webRequest) throws Exception {

    ResponseEntity<OAuth2Exception> translate = getExceptionTranslator().translate(e);
    webRequest.getResponse().setStatus(translate.getStatusCode().value());

    if (e instanceof ClientAuthenticationException || e instanceof RedirectMismatchException) {
        Map<String, Object> map = new HashMap<>();
        map.put("error", translate.getBody());
        if (e instanceof UnauthorizedClientException) {
            map.put("error_message_code", "login.invalid_idp");
        }/* w  ww.  j  a v  a 2  s .com*/
        return new ModelAndView(errorPage, map);
    }

    AuthorizationRequest authorizationRequest = null;
    try {
        authorizationRequest = getAuthorizationRequestForError(webRequest);
        String requestedRedirectParam = authorizationRequest.getRequestParameters()
                .get(OAuth2Utils.REDIRECT_URI);
        String requestedRedirect = redirectResolver.resolveRedirect(requestedRedirectParam,
                getClientServiceExtention().loadClientByClientId(authorizationRequest.getClientId(),
                        IdentityZoneHolder.get().getId()));
        authorizationRequest.setRedirectUri(requestedRedirect);
        String redirect = getUnsuccessfulRedirect(authorizationRequest, translate.getBody(),
                authorizationRequest.getResponseTypes().contains("token"));
        return new ModelAndView(new RedirectView(redirect, false, true, false));
    } catch (OAuth2Exception ex) {
        // If an AuthorizationRequest cannot be created from the incoming parameters it must be
        // an error. OAuth2Exception can be handled this way. Other exceptions will generate a standard 500
        // response.
        return new ModelAndView(errorPage, Collections.singletonMap("error", translate.getBody()));
    }

}