Build redirect url by requested authn context.

@param initialUrl   the initial url
@param authnRequest the authn request
@param request      the request
@return the redirect url
351790
protected String buildRedirectUrlByRequestedAuthnContext(final String initialUrl, final AuthnRequest authnRequest, final HttpServletRequest request) {
        val authenticationContextClassMappings = samlProfileHandlerConfigurationContext.getCasProperties()
            .getAuthn().getSamlIdp().getAuthenticationContextClassMappings();
        if (authnRequest.getRequestedAuthnContext() == null || authenticationContextClassMappings == null || authenticationContextClassMappings.isEmpty()) {
            return initialUrl;
        }

        val mappings = getAuthenticationContextMappings();

        val p =
            authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs()
                .stream()
                .filter(ref -> {
                    val clazz = ref.getAuthnContextClassRef();
                    return mappings.containsKey(clazz);
                })
                .findFirst();

        if (p.isPresent()) {
            val mappedClazz = mappings.get(p.get().getAuthnContextClassRef());
            return initialUrl + '&' + samlProfileHandlerConfigurationContext.getCasProperties()
                .getAuthn().getMfa().getRequestParameter() + '=' + mappedClazz;
        }

        return initialUrl;
    }
259928
private URL convertRequestToUrl(InternalRequest request) {
        String resourcePath = HttpUtils.normalizePath(request.getUri().getPath());

        // Removed the padding "/" that was already added into the request's resource path.
        if (resourcePath.startsWith("/")) {
            resourcePath = resourcePath.substring(1);
        }

        // Some http client libraries (e.g. Apache HttpClient) cannot handle
        // consecutive "/"s between URL authority and path components.
        // So we escape "////..." into "/%2F%2F%2F...", in the same way as how
        // we treat consecutive "/"s in AmazonS3Client#presignRequest(...)
        String urlPath = "/" + resourcePath;
        urlPath = urlPath.replaceAll("(?<=/)/", "%2F");
        String urlString = this.getEndpoint() + urlPath;

        boolean firstParam = true;
        for (String param : request.getParameters().keySet()) {
            if (firstParam) {
                urlString += "?";
                firstParam = false;
            } else {
                urlString += "&";
            }

            String value = request.getParameters().get(param);
            urlString += param + "=" + HttpUtils.normalize(value);
        }

        String authorization = request.getHeaders().get(Headers.AUTHORIZATION);
        if (authorization != null) {
            if (firstParam) {
                urlString += "?";
            } else {
                urlString += "&";
            }
            urlString += "authorization" + "=" + HttpUtils.normalize(authorization);
        }

        try {
            return new URL(urlString);
        } catch (MalformedURLException e) {
            throw new BceClientException("Unable to convert request to well formed URL: " + e.getMessage(), e);
        }
    }
772399
function request(req) {
        var clientID = getParam(req, 'client_id')
            , redirectURI = getParam(req, 'redirect_uri')
            , scope = getParam(req, 'scope')
            , state = getParam(req, 'state');

        if (!clientID) {
            throw new AuthorizationError('Missing required parameter: client_id', 'invalid_request');
        }

        if (scope) {
            for (var i = 0, len = separators.length; i < len; i++) {
                var separated = scope.split(separators[i]);
                // only separate on the first matching separator.  this allows for a sort
                // of separator "priority" (ie, favor spaces then fallback to commas)
                if (separated.length > 1) {
                    scope = separated;
                    break;
                }
            }

            if (!Array.isArray(scope)) {
                scope = [scope];
            }
        }

        return {
            clientID: clientID,
            redirectURI: redirectURI,
            scope: scope,
            state: state
        };
    }
223981
public void setRevocationURL(final String url) {
        license.add(Feature.Create.stringFeature(REVOCATION_URL, url));
    }
354958
protected RedirectAction build(final CasClient casClient, final WebContext context, final boolean renew, final boolean gateway) {
        val serviceUrl = casClient.computeFinalCallbackUrl(context);
        val casServerLoginUrl = casClient.getConfiguration().getLoginUrl();
        val redirectionUrl = casServerLoginUrl + (casServerLoginUrl.contains("?") ? "&" : "?")
            + CasProtocolConstants.PARAMETER_SERVICE + '=' + EncodingUtils.urlEncode(serviceUrl)
            + (renew ? '&' + CasProtocolConstants.PARAMETER_RENEW + "=true" : StringUtils.EMPTY)
            + (gateway ? '&' + CasProtocolConstants.PARAMETER_GATEWAY + "=true" : StringUtils.EMPTY);
        LOGGER.debug("Final redirect url is [{}]", redirectionUrl);
        return RedirectAction.redirect(redirectionUrl);
    }
1210967
public static void redirect(HttpServletRequest request, HttpServletResponse response,
                               String url) throws IOException {
        String redirectUrl;

        if (url.startsWith("/")) {
            redirectUrl = request.getContextPath() + url;
        } else {
            redirectUrl = url;
        }

        logger.debug("Redirecting to URL: {}", redirectUrl);

        response.sendRedirect(redirectUrl);
    }
21736
protected String buildUrl(Request request)
    {
        StringBuilder sb = new StringBuilder(512);
        sb.append(baseUrl).append(request.getEntityName()).append("/");
        if(request.getPath() != null)
            sb.append(request.getPath());

        String queryString = buildQueryString(request);
        if(queryString.length()>0)
        {
            sb.append("?").append(queryString);
        }

        return sb.toString();
    }
676057
def _get_redirect_url(self, request):
        
        if 'next' in request.session:
            next_url = request.session['next']
            del request.session['next']
        elif 'next' in request.GET:
            next_url = request.GET.get('next')
        elif 'next' in request.POST:
            next_url = request.POST.get('next')
        else:
            next_url = request.user.get_absolute_url()
        if not next_url:
            next_url = '/'
        return next_url
194765
protected ModelAndView buildCallbackViewViaRedirectUri(final J2EContext context, final String clientId,
                                                           final Authentication authentication, final OAuthCode code) {
        val attributes = authentication.getAttributes();
        val state = attributes.get(OAuth20Constants.STATE).get(0).toString();
        val nonce = attributes.get(OAuth20Constants.NONCE).get(0).toString();

        val redirectUri = context.getRequestParameter(OAuth20Constants.REDIRECT_URI);
        LOGGER.debug("Authorize request verification successful for client [{}] with redirect uri [{}]", clientId, redirectUri);

        var callbackUrl = redirectUri;
        callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.CODE, code.getId());
        if (StringUtils.isNotBlank(state)) {
            callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.STATE, state);
        }
        if (StringUtils.isNotBlank(nonce)) {
            callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.NONCE, nonce);
        }
        LOGGER.debug("Redirecting to URL [{}]", callbackUrl);
        val params = new LinkedHashMap<String, String>();
        params.put(OAuth20Constants.CODE, code.getId());
        params.put(OAuth20Constants.STATE, state);
        params.put(OAuth20Constants.NONCE, nonce);
        params.put(OAuth20Constants.CLIENT_ID, clientId);
        return buildResponseModelAndView(context, servicesManager, clientId, callbackUrl, params);
    }
316373
private String loginDestinationUrl(final HttpServletRequest request) {
        final HttpSession session = request.getSession();
        final String requestReferer = request.getHeader("referer");
        final String sessionReferer = (String) session
                .getAttribute(SESSION_REFERER_KEY);
        if (useReferer(requestReferer)) {
            return requestReferer;
        } else if (useReferer(sessionReferer)) {
            return sessionReferer;
        } else {
            return servletPath + "/person?db=schoeller&id=I1";
        }
    }
892492
public String setRedirectUrlIfNotDefined(HttpServletRequest req, ConvergedClientConfig clientConfig) {
        //String redirect_url = clientConfig.getRedirectUrlFromServerToClient();
        String redirect_url = null;
        // in oidc case, configimpl completely builds this url, in social we need to finish building it.
        if (clientConfig.isSocial()) {
            redirect_url = getRedirectUrlFromServerToClient(clientConfig.getId(), clientConfig.getContextPath(), clientConfig.getRedirectUrlFromServerToClient());
        } else {
            redirect_url = clientConfig.getRedirectUrlFromServerToClient();
        }

        // in oidc and social case, null unless redirectToRPHostAndPort specified.
        if (redirect_url == null || redirect_url.isEmpty()) {
            String uri = clientConfig.getContextPath() + "/redirect/" + clientConfig.getId();
            redirect_url = new OidcClientUtil().getRedirectUrl(req, uri);
        }
        redirect_url = clientConfig.getRedirectUrlWithJunctionPath(redirect_url);
        return redirect_url;
    }
667932
public Result redirect(String url) {
        status(Status.SEE_OTHER);
        with(HeaderNames.LOCATION, url);
        return this;
    }
326255
public String getRedirectUrlFromServerToClient(String clientId, String contextPath, String redirectToRPHostAndPort) {
        String redirectURL = null;
        if (redirectToRPHostAndPort != null && redirectToRPHostAndPort.length() > 0) {
            try {
                final String fHostPort = redirectToRPHostAndPort;
                @SuppressWarnings({ "unchecked", "rawtypes" })
                URL url = (URL) java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() {
                    @Override
                    public Object run() throws Exception {
                        return new URL(fHostPort);
                    }
                });
                int port = url.getPort();
                String path = url.getPath();
                if (path == null)
                    path = "";
                if (path.endsWith("/")) {
                    path = path.substring(0, path.length() - 1);
                }
                String entryPoint = path + contextPath + "/redirect/" + clientId;
                redirectURL = url.getProtocol() + "://" + url.getHost() + (port > 0 ? ":" + port : "");

                redirectURL = redirectURL + (entryPoint.startsWith("/") ? "" : "/") + entryPoint;
            } catch (Exception e) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "the value of redirectToRPHostAndPort might not valid. Please verify that the format is <protocol>://<host>:<port> " + redirectToRPHostAndPort
                            + "\n" + e.getMessage());
                }
            }
        }
        return redirectURL;
    }
988354
def start_auth(self, context, request_info):
        
        oidc_nonce = rndstr()
        oidc_state = rndstr()
        state_data = {
            NONCE_KEY: oidc_nonce,
            STATE_KEY: oidc_state
        }
        context.state[self.name] = state_data

        args = {
            "scope": self.config["client"]["auth_req_params"]["scope"],
            "response_type": self.config["client"]["auth_req_params"]["response_type"],
            "client_id": self.client.client_id,
            "redirect_uri": self.client.registration_response["redirect_uris"][0],
            "state": oidc_state,
            "nonce": oidc_nonce
        }
        args.update(self.config["client"]["auth_req_params"])
        auth_req = self.client.construct_AuthorizationRequest(request_args=args)
        login_url = auth_req.request(self.client.authorization_endpoint)
        return Redirect(login_url)
42423
def get_redirect_url(self, **kwargs):
        
        params = {
            'oauth_token': self.get_request_token().key,
        }
        return '%s?%s' % (self.auth_url, urllib.urlencode(params))
687906
def default_redirect(request, fallback_url, **kwargs):
    
    redirect_field_name = kwargs.get("redirect_field_name", "next")
    next = request.POST.get(redirect_field_name,
                            request.GET.get(redirect_field_name, ''))
    if not next:
        # try the session if available
        if hasattr(request, "session"):
            session_key_value = kwargs.get("session_key_value", "redirect_to")
            next = request.session.get(session_key_value)
    is_safe = functools.partial(
        ensure_safe_url,
        allowed_protocols=kwargs.get("allowed_protocols"),
        allowed_host=request.get_host()
    )
    redirect_to = next if next and is_safe(next) else fallback_url
    # perform one last check to ensure the URL is safe to redirect to. if it
    # is not then we should bail here as it is likely developer error and
    # they should be notified
    is_safe(redirect_to, raise_on_fail=True)
    return redirect_to
1265265
public static SamlEndpoint ofHttpRedirect(URI uri) {
        requireNonNull(uri, "uri");
        return new SamlEndpoint(uri, SamlBindingProtocol.HTTP_REDIRECT);
    }