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

The following examples show how to use com.netflix.zuul.context.RequestContext#addZuulResponseHeader() . 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: MyZuulFilter.java    From springcloud-study with Apache License 2.0 6 votes vote down vote up
@Override
	public Object run() throws ZuulException {
		//获取请求的上下文类 注意是:com.netflix.zuul.context包下的
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		ctx.addZuulResponseHeader("Content-type", "text/json;charset=UTF-8");
		ctx.getResponse().setCharacterEncoding("UTF-8");
		System.out.println("请求地址:"+request.getRequestURI());
		String token = request.getParameter("token");
		String msg="请求成功!";
		if(token==null) {
			//使其不进行转发
		   ctx.setSendZuulResponse(false);
		   msg="请求失败!原因是token为空!";
		   ctx.setResponseBody(msg);
		   ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
		   //或者添加一个额外参数也可以 传递参数可以使用
//		   ctx.set("checkAuth",false);
		}
		System.out.println(msg);
		return msg;
	}
 
Example 2
Source File: TokenFilter.java    From xmfcn-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 处理逻辑
 *
 * @return
 */
@Override
public Object run() {
    RequestContext requestContext = RequestContext.getCurrentContext();
    HttpServletRequest request = requestContext.getRequest();
    HttpServletResponse response = requestContext.getResponse();
    String sourceCode = request.getParameter("sourceCode");
    String dbCode = sysCommonService.getDictValue(ConstantUtil.DICT_TYPE_BASE_CONFIG, "sourceCode");
    if (StringUtil.isBlank(dbCode)||!dbCode.equals(sourceCode)) {
        requestContext.setSendZuulResponse(false);// 对该请求不路由
        requestContext.set("isSuccess", false);// 设值,让下一个Filter看到上一个Filter的状态
        // 构建返回信息
        RetData retData = new RetData();
        retData.setCode(ResultCodeMessage.UNAUTHORIZED);
        retData.setMessage(ResultCodeMessage.UNAUTHORIZED_MESSAGE);
        String jsonString = JSON.toJSONString(retData, SerializerFeature.WriteMapNullValue);
        requestContext.setResponseBody(jsonString);
        requestContext.addZuulResponseHeader("content-type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        return response;
    }
    requestContext.set("isSuccess", true);// 设值,让下一个Filter看到上一个Filter的状态
    return null;
}
 
Example 3
Source File: ConvertAuthTokenInUriToCookieFilter.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
public Object run() {
    RequestContext context = RequestContext.getCurrentContext();
    AuthConfigurationProperties.CookieProperties cp = authConfigurationProperties.getCookieProperties();
    if ((context.getRequestQueryParams() != null) && context.getRequestQueryParams().containsKey(cp.getCookieName())) {
        HttpServletResponse servletResponse = context.getResponse();
        Cookie cookie = new Cookie(cp.getCookieName(), context.getRequestQueryParams().get(cp.getCookieName()).get(0));
        cookie.setPath(cp.getCookiePath());
        cookie.setSecure(true);
        cookie.setHttpOnly(true);
        cookie.setMaxAge(cp.getCookieMaxAge());
        cookie.setComment(cp.getCookieComment());
        servletResponse.addCookie(cookie);

        String url = context.getRequest().getRequestURL().toString();
        String newUrl;
        if (url.endsWith("/apicatalog/")) {
            newUrl = url + "#/dashboard";
        } else {
            newUrl = url;
        }
        context.addZuulResponseHeader("Location", newUrl);
        context.setResponseStatusCode(HttpServletResponse.SC_MOVED_TEMPORARILY);
    }
    return null;
}
 
Example 4
Source File: PageRedirectionFilterTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void sameServerAndUrlMatched() throws Exception {
    RoutedService currentService = new RoutedService("ui", "ui", "/");
    RoutedServices routedServices = new RoutedServices();
    routedServices.addRoutedService(currentService);
    this.filter.addRoutedServices(SERVICE_ID, routedServices);

    when(discoveryClient.getInstances(SERVICE_ID)).thenReturn(Collections.singletonList(
        new DefaultServiceInstance(SERVICE_ID, TARGET_SERVER_HOST, TARGET_SERVER_PORT, true)
    ));

    response.setStatus(302);
    String relativePath = "/some/path/login.html";
    String location = mockLocationSameServer(relativePath);
    final RequestContext ctx = RequestContext.getCurrentContext();
    ctx.addZuulResponseHeader(LOCATION, location);
    this.filter.run();

    Optional<Pair<String, String>> locationHeader = ctx.getZuulResponseHeaders()
        .stream()
        .filter(stringPair -> LOCATION.equals(stringPair.first()))
        .findFirst();

    verifyLocationUpdatedSameServer(locationHeader.map(Pair::second).orElse(null), location,
        "/" + currentService.getGatewayUrl() + "/" + SERVICE_ID + relativePath);
}
 
Example 5
Source File: BaseFilter.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 网关抛异常
 *
 * @param body
 * @param code
 */
protected void setFailedRequest(String body, int code) {
    log.debug("Reporting error ({}): {}", code, body);
    RequestContext ctx = RequestContext.getCurrentContext();
    // 返回错误码
    ctx.setResponseStatusCode(code);
    ctx.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
    if (ctx.getResponseBody() == null) {
        // 返回错误内容
        ctx.setResponseBody(body);
        // 过滤该请求,不对其进行路由
        ctx.setSendZuulResponse(false);
    }
}
 
Example 6
Source File: SlashFilter.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object run() {
    RequestContext context = RequestContext.getCurrentContext();
    String proxy = UrlUtils.removeFirstAndLastSlash((String) context.get(PROXY_KEY));
    if (proxy != null && !proxy.isEmpty()) {
        context.setSendZuulResponse(false);
        context.addZuulResponseHeader("Location", "/" + proxy + "/");
        context.setResponseStatusCode(HttpServletResponse.SC_MOVED_TEMPORARILY);
    }
    return null;
}
 
Example 7
Source File: EncodedCharactersFilter.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
private void rejectRequest(RequestContext ctx) {
    Message message = messageService.createMessage("org.zowe.apiml.gateway.requestContainEncodedCharacter",
        ctx.get(SERVICE_ID_KEY), ctx.getRequest().getRequestURI());

    ctx.setSendZuulResponse(false);
    ctx.addZuulResponseHeader("Content-Type", "application/json");
    ctx.setResponseStatusCode(HttpStatus.BAD_REQUEST.value());

    String response = getMessageString(message);
    ctx.setResponseBody(response);
}
 
Example 8
Source File: PageRedirectionFilterTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void sameServerAndUrlNotMatched() {
    String serviceUrl = "/discoverableclient/api/v1";
    RoutedService currentService = new RoutedService("api-v1", "api/v1", serviceUrl);
    RoutedServices routedServices = new RoutedServices();
    routedServices.addRoutedService(currentService);
    this.filter.addRoutedServices(SERVICE_ID, routedServices);

    when(discoveryClient.getInstances(SERVICE_ID)).thenReturn(Collections.singletonList(
        new DefaultServiceInstance(SERVICE_ID, TARGET_SERVER_HOST, TARGET_SERVER_PORT, true)
    ));

    response.setStatus(304);
    String relativePath = "/some/path/login.html";
    String location = mockLocationSameServer(relativePath);

    final RequestContext ctx = RequestContext.getCurrentContext();
    ctx.addZuulResponseHeader(LOCATION, location);
    this.filter.run();

    Optional<Pair<String, String>> locationHeader = ctx.getZuulResponseHeaders()
        .stream()
        .filter(stringPair -> LOCATION.equals(stringPair.first()))
        .findFirst();

    verifyLocationNotUpdated(locationHeader.map(Pair::second).orElse(null), location);
}
 
Example 9
Source File: PageRedirectionFilterTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void hostRegisteredAndUrlMatched() throws Exception {
    //route for current service
    RoutedService currentService = new RoutedService("ui", "ui", "/");
    RoutedServices routedServices = new RoutedServices();
    routedServices.addRoutedService(currentService);
    this.filter.addRoutedServices(SERVICE_ID, routedServices);
    //route for other service
    String serviceUrl = "/discoverableclient/api/v1";
    RoutedService otherService = new RoutedService("ui-v1", "ui/v1", serviceUrl);
    RoutedServices otherRoutedServices = new RoutedServices();
    otherRoutedServices.addRoutedService(otherService);
    this.filter.addRoutedServices(OTHER_SERVICE_ID, otherRoutedServices);

    when(discoveryClient.getInstances(SERVICE_ID)).thenReturn(Collections.singletonList(
        new DefaultServiceInstance(SERVICE_ID, TARGET_SERVER_HOST, TARGET_SERVER_PORT, true)
    ));
    when(discoveryClient.getInstances(OTHER_SERVICE_ID)).thenReturn(Collections.singletonList(
        new DefaultServiceInstance(OTHER_SERVICE_ID, OTHER_SERVICE_SERVER_HOST, OTHER_SERVICE_SERVER_PORT, true)
    ));
    when(discoveryClient.getServices()).thenReturn(Arrays.asList(SERVICE_ID, OTHER_SERVICE_ID));

    response.setStatus(307);
    String relativePath = "/some/path/login.html";
    String location = mockLocationDSServer(serviceUrl + relativePath);

    final RequestContext ctx = RequestContext.getCurrentContext();
    ctx.addZuulResponseHeader(LOCATION, location);
    this.filter.run();

    Optional<Pair<String, String>> locationHeader = ctx.getZuulResponseHeaders()
        .stream()
        .filter(stringPair -> LOCATION.equals(stringPair.first()))
        .findFirst();

    this.verifyLocationUpdatedSameServer(locationHeader.map(Pair::second).orElse(null), location,
        "/" + otherService.getGatewayUrl() + "/" + OTHER_SERVICE_ID + relativePath);
}
 
Example 10
Source File: PageRedirectionFilterTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void differentServerAndHostPortNotInDSAndLocationContainsGatewayURL() {
    //route for current service
    RoutedService currentService = new RoutedService("ui", "ui", "/");
    RoutedServices routedServices = new RoutedServices();
    routedServices.addRoutedService(currentService);
    this.filter.addRoutedServices(SERVICE_ID, routedServices);
    //route for other service
    String serviceUrl = "/discoverableclient/api/v1";
    RoutedService otherService = new RoutedService("api-v1", "api/v1", serviceUrl);
    RoutedServices otherRoutedServices = new RoutedServices();
    otherRoutedServices.addRoutedService(otherService);
    this.filter.addRoutedServices(OTHER_SERVICE_ID, otherRoutedServices);

    when(discoveryClient.getInstances(SERVICE_ID)).thenReturn(Collections.singletonList(
        new DefaultServiceInstance(SERVICE_ID, TARGET_SERVER_HOST, TARGET_SERVER_PORT, true)
    ));
    when(discoveryClient.getInstances(OTHER_SERVICE_ID)).thenReturn(Collections.singletonList(
        new DefaultServiceInstance(OTHER_SERVICE_ID, OTHER_SERVICE_SERVER_HOST, OTHER_SERVICE_SERVER_PORT, true)
    ));
    when(discoveryClient.getServices()).thenReturn(Arrays.asList(SERVICE_ID, OTHER_SERVICE_ID));

    response.setStatus(307);
    String relativePath = "/some/path/login.html";
    String location = mockLocationOtherServer(serviceUrl + relativePath);

    final RequestContext ctx = RequestContext.getCurrentContext();
    ctx.addZuulResponseHeader(LOCATION, location);
    this.filter.run();

    Optional<Pair<String, String>> locationHeader = ctx.getZuulResponseHeaders()
        .stream()
        .filter(stringPair -> LOCATION.equals(stringPair.first()))
        .findFirst();

    this.verifyLocationNotUpdated(locationHeader.map(Pair::second).orElse(null), location);
}
 
Example 11
Source File: PageRedirectionFilterTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void serviceUrlEndWithSlash() throws Exception {
    String serviceUrl = "/discoverableclient";
    RoutedService currentService = new RoutedService("ui-v1", "ui/v1", serviceUrl + "/");
    RoutedServices routedServices = new RoutedServices();
    routedServices.addRoutedService(currentService);
    this.filter.addRoutedServices(SERVICE_ID, routedServices);

    when(discoveryClient.getInstances(SERVICE_ID)).thenReturn(Collections.singletonList(
        new DefaultServiceInstance(SERVICE_ID, TARGET_SERVER_HOST, TARGET_SERVER_PORT, true)
    ));

    response.setStatus(302);
    String relativePath = "/some/path/login.html";
    String location = mockLocationSameServer(serviceUrl + relativePath);
    final RequestContext ctx = RequestContext.getCurrentContext();
    ctx.addZuulResponseHeader(LOCATION, location);
    this.filter.run();

    Optional<Pair<String, String>> locationHeader = ctx.getZuulResponseHeaders()
        .stream()
        .filter(stringPair -> LOCATION.equals(stringPair.first()))
        .findFirst();

    verifyLocationUpdatedSameServer(locationHeader.map(Pair::second).orElse(null), location,
        "/" + currentService.getGatewayUrl() + "/" + SERVICE_ID + relativePath);
}
 
Example 12
Source File: ZuulRateLimitFilter.java    From bucket4j-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public Object run() {
	RequestContext context = getCurrentRequestContext();
	HttpServletRequest request = context.getRequest();

       Long remainingLimit = null;
	for (RateLimitCheck<HttpServletRequest> rl : filterConfig.getRateLimitChecks()) {
		ConsumptionProbeHolder probeHolder = rl.rateLimit(request, false);
		if (probeHolder != null && probeHolder.getConsumptionProbe() != null) {
			ConsumptionProbe probe = probeHolder.getConsumptionProbe();
			if (probe.isConsumed()) {
				remainingLimit = getRemainingLimit(remainingLimit, probe);
			} else {
				context.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
				context.addZuulResponseHeader("X-Rate-Limit-Retry-After-Seconds", "" + TimeUnit.NANOSECONDS.toSeconds(probe.getNanosToWaitForRefill()));
				context.setResponseBody(filterConfig.getHttpResponseBody());
				context.setSendZuulResponse(false);
				break;
			}
			if(filterConfig.getStrategy().equals(RateLimitConditionMatchingStrategy.FIRST)) {
				break;
			}
		}
	};

	return null;
}