Java Code Examples for com.netflix.zuul.context.RequestContext#put()

The following examples show how to use com.netflix.zuul.context.RequestContext#put() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CacheInterceptorService.java    From heimdall with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if the request is in cache. If true then returns the cached response, otherwise
 * continues the request normally and signals to create the cache for this request.
 *
 * @param cacheName   Cache name provided
 * @param timeToLive  How much time the cache will live (0 or less to live forever)
 * @param headers     List of headers that when present signal that the request should be cached
 * @param queryParams List of queryParams that when present signal that the request should be cached
 */
public void cacheInterceptor(String cacheName, Long timeToLive, List<String> headers, List<String> queryParams) {

    RequestContext context = RequestContext.getCurrentContext();

    boolean responseFromCache = false;

    if (shouldCache(context, headers, queryParams)) {
        RBucket<ApiResponse> rBucket = redissonClientCacheInterceptor.getBucket(createCacheKey(context, cacheName, headers, queryParams));

        if (rBucket.get() == null) {
            context.put(CACHE_BUCKET, rBucket);
            context.put(CACHE_TIME_TO_LIVE, timeToLive);
        } else {
            ApiResponse response = rBucket.get();

            helper.call().response().header().addAll(response.getHeaders());
            helper.call().response().setBody(response.getBody());
            helper.call().response().setStatus(response.getStatus());
            context.setSendZuulResponse(false);
            responseFromCache = true;
        }
    }

    TraceContextHolder.getInstance().getActualTrace().setCache(responseFromCache);
}
 
Example 2
Source File: MultiVersionServerSupportFilter.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
@Override
public Object run() {
    Route route = route();

    RequestContext ctx = RequestContext.getCurrentContext();
    final String requestURI = URL_PATH_HELPER.getPathWithinApplication(ctx.getRequest());
    String version = ctx.getRequest().getHeader("serviceSuffix");

    if (StrUtil.isEmpty(version)) {
        version = ctx.getRequest().getParameter("serviceSuffix");
    }

    StringBuilder serviceId = new StringBuilder(route.getLocation());
    if (StrUtil.isNotEmpty(version)) {
        serviceId.append("-");
        serviceId.append(version);
    }
    String serviceIdStr = serviceId.toString();
    List<ServiceInstance> instances = discoveryClient.getInstances(serviceIdStr);
    log.debug("serviceIdStr={}, size={}", serviceIdStr, instances.size());
    if (!instances.isEmpty()) {
        ctx.put(REQUEST_URI_KEY, requestURI.substring(requestURI.indexOf('/', 1)));
        ctx.set(SERVICE_ID_KEY, serviceIdStr);
        ctx.setRouteHost(null);
        ctx.addOriginResponseHeader(SERVICE_ID_HEADER, serviceIdStr);

    }
    return null;
}
 
Example 3
Source File: EnvironmentForward.java    From pulsar-manager with Apache License 2.0 5 votes vote down vote up
private Object forwardRequest(RequestContext ctx, HttpServletRequest request, String serviceUrl) {
    ctx.put(REQUEST_URI_KEY, request.getRequestURI());
    try {
        Map<String, String> authHeader = pulsarAdminService.getAuthHeader(serviceUrl);
        authHeader.entrySet().forEach(entry -> ctx.addZuulRequestHeader(entry.getKey(), entry.getValue()));
        ctx.setRouteHost(new URL(serviceUrl));
        pulsarEvent.parsePulsarEvent(request.getRequestURI(), request);
        log.info("Forward request to {} @ path {}",
                serviceUrl, request.getRequestURI());
    } catch (MalformedURLException e) {
        log.error("Route forward to {} path {} error: {}",
                serviceUrl, request.getRequestURI(), e.getMessage());
    }
    return null;
}
 
Example 4
Source File: SwitchEnableCorsFilter.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
		FilterChain filterChain) throws ServletException, IOException {

	RequestContext ctx = RequestContext.getCurrentContext();
	// /api/tax/list -> tax 
	String routePath = request.getRequestURI().substring(configManager.getContextpth().length() + 1);
	if(routePath.contains("/"))routePath = routePath.substring(0,routePath.indexOf("/"));
	if(ctx != null){
		ctx.put(PlatformConfigManager.CONTEXT_ROUTE_NAME, routePath);
	}
	
	Pattern pattern = configManager.getCorsEnabledUriPattern(routePath);
	boolean corsEnabled = pattern != null && pattern.matcher(request.getRequestURI()).matches();
	
	if (corsEnabled && CorsUtils.isCorsRequest(request)) {
		CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(request);
		if (corsConfiguration != null) {
			boolean isValid = this.processor.processRequest(corsConfiguration, request, response);
			if (!isValid || CorsUtils.isPreFlightRequest(request)) {
				return;
			}
		}
	}

	filterChain.doFilter(request, response);
}
 
Example 5
Source File: ClientIdInterceptorService.java    From heimdall with Apache License 2.0 5 votes vote down vote up
private void buildResponse(String message) {
    RequestContext ctx = RequestContext.getCurrentContext();
    ctx.setSendZuulResponse(false);
    ctx.put(INTERRUPT, true);
    ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
    ctx.setResponseBody(message);
}
 
Example 6
Source File: AccessTokenInterceptorService.java    From heimdall with Apache License 2.0 5 votes vote down vote up
private void buildResponse(String message) {
    RequestContext ctx = RequestContext.getCurrentContext();
    ctx.setSendZuulResponse(false);
    ctx.put(INTERRUPT, true);
    ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
    ctx.setResponseBody(message);
}
 
Example 7
Source File: ProxyRedirectFilter.java    From spring-cloud-netflix-zuul-websocket with Apache License 2.0 5 votes vote down vote up
@Override
public boolean shouldFilter() {
	RequestContext ctx = RequestContext.getCurrentContext();
	boolean isRedirect = ctx.getResponseStatusCode() == 301 || ctx.getResponseStatusCode() == 302;
	if (!isRedirect)
		return false;

	boolean hasCorrectLocation = false;

	List<Pair<String, String>> zuulResponseHeaders = ctx.getZuulResponseHeaders();
	for (Pair<String, String> zuulResponseHeader : zuulResponseHeaders) {
		if ("Location".equalsIgnoreCase(zuulResponseHeader.first())) {
			HttpServletRequest request = ctx.getRequest();
			String path = urlPathHelper.getPathWithinApplication(request);
			Route route = routeLocator.getMatchingRoute(path);
			UriComponents redirectTo = ServletUriComponentsBuilder
					.fromHttpUrl(zuulResponseHeader.second()).build();
			UriComponents routeLocation = ServletUriComponentsBuilder
					.fromHttpUrl(route.getLocation()).build();

			if (redirectTo.getHost().equalsIgnoreCase(routeLocation.getHost())
					&& redirectTo.getPort() == routeLocation.getPort()) {
				String toLocation = ServletUriComponentsBuilder
						.fromHttpUrl(zuulResponseHeader.second())
						.host(request.getServerName())
						.port(request.getServerPort())
						.replacePath(
								buildRoutePath(route, zuulResponseHeader.second()))
						.build().toUriString();

				ctx.put(REDIRECT_TO_URL, toLocation);
				hasCorrectLocation = true;
				break;
			}
		}
	}

	return hasCorrectLocation;
}
 
Example 8
Source File: QueryParamServiceIdPreFilter.java    From sample-zuul-filters with Apache License 2.0 5 votes vote down vote up
public Object run() {
	RequestContext ctx = getCurrentContext();
	HttpServletRequest request = ctx.getRequest();
	// put the serviceId in `RequestContext`
	ctx.put("serviceId", request.getParameter("service"));
	return null;
}
 
Example 9
Source File: SentinelZuulPreFilter.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
@Override
public Object run() throws ZuulException {
    RequestContext ctx = RequestContext.getCurrentContext();
    String origin = parseOrigin(ctx.getRequest());
    String routeId = (String)ctx.get(ZuulConstant.PROXY_ID_KEY);

    Deque<AsyncEntry> asyncEntries = new ArrayDeque<>();
    String fallBackRoute = routeId;
    try {
        if (StringUtil.isNotBlank(routeId)) {
            ContextUtil.enter(GATEWAY_CONTEXT_ROUTE_PREFIX + routeId, origin);
            doSentinelEntry(routeId, RESOURCE_MODE_ROUTE_ID, ctx, asyncEntries);
        }

        Set<String> matchingApis = pickMatchingApiDefinitions(ctx);
        if (!matchingApis.isEmpty() && ContextUtil.getContext() == null) {
            ContextUtil.enter(ZuulConstant.ZUUL_DEFAULT_CONTEXT, origin);
        }
        for (String apiName : matchingApis) {
            fallBackRoute = apiName;
            doSentinelEntry(apiName, RESOURCE_MODE_CUSTOM_API_NAME, ctx, asyncEntries);
        }
    } catch (BlockException ex) {
        ZuulBlockFallbackProvider zuulBlockFallbackProvider = ZuulBlockFallbackManager.getFallbackProvider(
            fallBackRoute);
        BlockResponse blockResponse = zuulBlockFallbackProvider.fallbackResponse(fallBackRoute, ex);
        // Prevent routing from running
        ctx.setRouteHost(null);
        ctx.set(ZuulConstant.SERVICE_ID_KEY, null);

        // Set fallback response.
        ctx.setResponseBody(blockResponse.toString());
        ctx.setResponseStatusCode(blockResponse.getCode());
        // Set Response ContentType
        ctx.getResponse().setContentType("application/json; charset=utf-8");
    } finally {
        // We don't exit the entry here. We need to exit the entries in post filter to record Rt correctly.
        // So here the entries will be carried in the request context.
        if (!asyncEntries.isEmpty()) {
            ctx.put(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY, asyncEntries);
        }
    }
    return null;
}
 
Example 10
Source File: SentinelZuulPreFilter.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@Override
public Object run() throws ZuulException {
    RequestContext ctx = RequestContext.getCurrentContext();
    String origin = parseOrigin(ctx.getRequest());
    String routeId = (String)ctx.get(ZuulConstant.PROXY_ID_KEY);

    Deque<EntryHolder> holders = new ArrayDeque<>();
    String fallBackRoute = routeId;
    try {
        if (StringUtil.isNotBlank(routeId)) {
            ContextUtil.enter(GATEWAY_CONTEXT_ROUTE_PREFIX + routeId, origin);
            doSentinelEntry(routeId, RESOURCE_MODE_ROUTE_ID, ctx, holders);
        }

        Set<String> matchingApis = pickMatchingApiDefinitions(ctx);
        if (!matchingApis.isEmpty() && ContextUtil.getContext() == null) {
            ContextUtil.enter(ZuulConstant.ZUUL_DEFAULT_CONTEXT, origin);
        }
        for (String apiName : matchingApis) {
            fallBackRoute = apiName;
            doSentinelEntry(apiName, RESOURCE_MODE_CUSTOM_API_NAME, ctx, holders);
        }
    } catch (BlockException ex) {
        ZuulBlockFallbackProvider zuulBlockFallbackProvider = ZuulBlockFallbackManager.getFallbackProvider(
            fallBackRoute);
        BlockResponse blockResponse = zuulBlockFallbackProvider.fallbackResponse(fallBackRoute, ex);
        // Prevent routing from running
        ctx.setRouteHost(null);
        ctx.set(ZuulConstant.SERVICE_ID_KEY, null);

        // Set fallback response.
        ctx.setResponseBody(blockResponse.toString());
        ctx.setResponseStatusCode(blockResponse.getCode());
        // Set Response ContentType
        ctx.getResponse().setContentType("application/json; charset=utf-8");
    } finally {
        // We don't exit the entry here. We need to exit the entries in post filter to record Rt correctly.
        // So here the entries will be carried in the request context.
        if (!holders.isEmpty()) {
            ctx.put(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY, holders);
        }
    }
    return null;
}
 
Example 11
Source File: GlobalFilter.java    From oneplatform with Apache License 2.0 4 votes vote down vote up
@Override
public Object run() {
	//
	MDC.clear();
	RequestContext ctx = RequestContext.getCurrentContext();
	try {
		HttpServletRequest request = ctx.getRequest();
		
		RequestContextHelper.set(request, ctx.getResponse());
		
		ctx.put(PlatformConfigManager.CONTEXT_CLIENT_IP, IpUtils.getIpAddr(request)); 
		
		String invokeIp = request.getHeader(WebConstants.HEADER_INVOKER_IP);
		if(StringUtils.isNotBlank(invokeIp)){
			ctx.addZuulRequestHeader(WebConstants.HEADER_INVOKER_IP,invokeIp);
		}
		
		ctx.addZuulRequestHeader(WebConstants.HEADER_AUTH_TOKEN, SecurityCryptUtils.generateAuthCode());
		
		String proto = request.getHeader(WebConstants.HEADER_FORWARDED_PROTO);
		if(StringUtils.isNotBlank(proto)){
			ctx.addZuulRequestHeader(WebConstants.HEADER_FORWARDED_ORIGN_PROTO,proto);
		}
		//
		String routeName = Objects.toString(ctx.get(PlatformConfigManager.CONTEXT_ROUTE_NAME),null);
		if(routeName == null){			
			routeName = request.getRequestURI().substring(configManager.getContextpth().length() + 1);
			if(routeName.contains("/"))routeName = routeName.substring(0,routeName.indexOf("/"));
			ctx.put(PlatformConfigManager.CONTEXT_ROUTE_NAME, routeName);
		}
		//
		Cookie[] cookies = request.getCookies();
		if(cookies != null){
			for (Cookie cookie : cookies) {
				if(cookie.getName().startsWith(WebConstants.HEADER_PREFIX)){
					ctx.addZuulRequestHeader(cookie.getName(),cookie.getValue());
				}
			}
		}
	} catch (Exception e) {
		String error = "Error during filtering[GlobalFilter]";
		log.error(error,e);
		WebUtils.responseOutJson(ctx.getResponse(), JsonUtils.toJson(new WrapperResponse<>(500, error)));
	}
	
	return null;
}
 
Example 12
Source File: HeimdallDecorationFilter.java    From heimdall with Apache License 2.0 4 votes vote down vote up
protected void process() {

        RequestContext ctx = RequestContext.getCurrentContext();
        final String requestURI = getPathWithoutStripSuffix(ctx.getRequest());

        if (pathMatcher.match(ConstantsPath.PATH_MANAGER_PATTERN, requestURI) || "/error".equals(requestURI)) {
            ctx.set(FORWARD_TO_KEY, requestURI);
            return;
        }

        final String method = ctx.getRequest().getMethod().toUpperCase();
        HeimdallRoute heimdallRoute = getMatchingHeimdallRoute(requestURI, method, ctx);

        if (heimdallRoute != null) {

            if (heimdallRoute.isMethodNotAllowed()) {
                ctx.setSendZuulResponse(false);
                ctx.setResponseStatusCode(HttpStatus.METHOD_NOT_ALLOWED.value());
                ctx.setResponseBody(HttpStatus.METHOD_NOT_ALLOWED.getReasonPhrase());
                return;
            }

            if (heimdallRoute.getRoute() == null || heimdallRoute.getRoute().getLocation() == null) {
                log.warn("Environment not configured for this location: {} and inbound: {}", ctx.getRequest().getRequestURL(), requestURI);
                ctx.setSendZuulResponse(false);
                ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
                ctx.setResponseBody("Environment not configured for this inbound");
                ctx.getResponse().setContentType(MediaType.TEXT_PLAIN_VALUE);
                TraceContextHolder.getInstance().getActualTrace().setRequest(requestHelper.dumpRequest());
                return;
            }

            String location = heimdallRoute.getRoute().getLocation();
            ctx.put(REQUEST_URI_KEY, heimdallRoute.getRoute().getPath());
            ctx.put(PROXY_KEY, heimdallRoute.getRoute().getId());
            if (!heimdallRoute.getRoute().isCustomSensitiveHeaders()) {
                this.proxyRequestHelper.addIgnoredHeaders(this.properties.getSensitiveHeaders().toArray(new String[0]));
            } else {
                this.proxyRequestHelper.addIgnoredHeaders(heimdallRoute.getRoute().getSensitiveHeaders().toArray(new String[0]));
            }

            if (heimdallRoute.getRoute().getRetryable() != null) {
                ctx.put(RETRYABLE_KEY, heimdallRoute.getRoute().getRetryable());
            }

            if (location.startsWith(HTTP_SCHEME + ":") || location.startsWith(HTTPS_SCHEME + ":")) {
                ctx.setRouteHost(UrlUtil.getUrl(location));
                ctx.addOriginResponseHeader(SERVICE_HEADER, location);
            } else if (location.startsWith(FORWARD_LOCATION_PREFIX)) {
                ctx.set(FORWARD_TO_KEY, StringUtils.cleanPath(location.substring(FORWARD_LOCATION_PREFIX.length()) + heimdallRoute.getRoute().getPath()));
                ctx.setRouteHost(null);
                return;
            } else {
                // set serviceId for use in filters.route.RibbonRequest
                ctx.set(SERVICE_ID_KEY, location);
                ctx.setRouteHost(null);
                ctx.addOriginResponseHeader(SERVICE_ID_HEADER, location);
            }
            if (this.properties.isAddProxyHeaders()) {
                addProxyHeaders(ctx);
                String xforwardedfor = ctx.getRequest().getHeader(X_FORWARDED_FOR_HEADER);
                String remoteAddr = ctx.getRequest().getRemoteAddr();
                if (xforwardedfor == null) {
                    xforwardedfor = remoteAddr;
                } else if (!xforwardedfor.contains(remoteAddr)) { // Prevent duplicates
                    xforwardedfor += ", " + remoteAddr;
                }
                ctx.addZuulRequestHeader(X_FORWARDED_FOR_HEADER, xforwardedfor);
            }
            if (this.properties.isAddHostHeader()) {
                ctx.addZuulRequestHeader(HttpHeaders.HOST, toHostHeader(ctx.getRequest()));
            }
        } else {
            log.warn("No route found for uri: " + requestURI);
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(HttpStatus.NOT_FOUND.value());
            ctx.setResponseBody(HttpStatus.NOT_FOUND.getReasonPhrase());
            ctx.getResponse().setContentType(MediaType.TEXT_PLAIN_VALUE);
            TraceContextHolder.getInstance().getActualTrace().setRequest(requestHelper.dumpRequest());
        }
    }
 
Example 13
Source File: HeimdallDecorationFilter.java    From heimdall with Apache License 2.0 4 votes vote down vote up
protected HeimdallRoute getMatchingHeimdallRoute(String requestURI, String method, RequestContext ctx) {

        boolean auxMatch = false;
        for (Entry<String, ZuulRoute> entry : routeLocator.getAtomicRoutes().get().entrySet()) {
            if (entry.getKey() != null) {
                String pattern = entry.getKey();
                if (this.pathMatcher.match(pattern, requestURI)) {

                    auxMatch = true;
                    List<Credential> credentials = credentialRepository.findByPattern(pattern);
                    Credential credential = null;
                    if (Objects.nonNull(credentials) && !credentials.isEmpty()) {

                        if (method.equals(HttpMethod.OPTIONS.name())) {
                            Optional<Credential> first = credentials.stream().findFirst();
                            if (first.get().isCors()) {
                            	credential = first.get();
                            }
                        }

                        if (Objects.isNull(credential)) {
                        	credential = credentials.stream()
                                    .filter(o -> o.getMethod().equals(HttpMethod.ALL.name()) || method.equals(o.getMethod().toUpperCase()))
                                    .findFirst().orElse(null);
                        }
                    }

                    if (credential != null) {
                        ZuulRoute zuulRoute = entry.getValue();

                        String basePath = credential.getApiBasePath();
                        requestURI = org.apache.commons.lang.StringUtils.removeStart(requestURI, basePath);

                        ctx.put(PATTERN, org.apache.commons.lang.StringUtils.removeStart(pattern, basePath));
                        ctx.put(API_NAME, credential.getApiName());
                        ctx.put(API_ID, credential.getApiId());
                        ctx.put(RESOURCE_ID, credential.getResourceId());
                        ctx.put(OPERATION_ID, credential.getOperationId());
                        ctx.put(OPERATION_PATH, credential.getOperationPath());

                        String host = ctx.getRequest().getHeader("Host");

                        EnvironmentInfo environment;
                        String location = null;
                        if (host != null && !host.isEmpty()) {
                            environment = environmentInfoRepository.findByApiIdAndEnvironmentInboundURL(credential.getApiId(), host.toLowerCase());
                        } else {
                            environment = environmentInfoRepository.findByApiIdAndEnvironmentInboundURL(credential.getApiId(), ctx.getRequest().getRequestURL().toString().toLowerCase());
                        }

                        if (environment != null) {
                            location = environment.getOutboundURL();
                            ctx.put(ENVIRONMENT_VARIABLES, environment.getVariables());
                        }

                        Route route = new Route(zuulRoute.getId(),
                                requestURI,
                                location,
                                "",
                                zuulRoute.getRetryable() != null ? zuulRoute.getRetryable() : false,
                                zuulRoute.isCustomSensitiveHeaders() ? zuulRoute.getSensitiveHeaders() : null);

                        TraceContextHolder traceContextHolder = TraceContextHolder.getInstance();

                        traceContextHolder.getActualTrace().setApiId(credential.getApiId());
                        traceContextHolder.getActualTrace().setApiName(credential.getApiName());
                        traceContextHolder.getActualTrace().setResourceId(credential.getResourceId());
                        traceContextHolder.getActualTrace().setOperationId(credential.getOperationId());

                        return new HeimdallRoute(pattern, route, false);
                    } else {

                        ctx.put(INTERRUPT, true);
                    }
                }
            }
        }

        if (auxMatch) {
            return new HeimdallRoute().methodNotAllowed();
        }

        return null;
    }