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

The following examples show how to use com.netflix.zuul.context.RequestContext#setResponseStatusCode() . 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: MyFilter.java    From kitty with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Object run() throws ZuulException {
    // filter需要执行的具体操作
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    String token = request.getParameter("token");
    System.out.println(token);
    if(token==null){
        log.warn("there is no request token");
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(401);
        try {
            ctx.getResponse().getWriter().write("there is no request token");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    log.info("ok");
    return null;
}
 
Example 2
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 3
Source File: LoginFilter.java    From cloud-template with MIT License 6 votes vote down vote up
/**
 * 过滤器的具体业务逻辑
 *
 * @return
 * @throws ZuulException
 */
@Override
public Object run() throws ZuulException {
    RequestContext currentContext = RequestContext.getCurrentContext();
    HttpServletRequest request = currentContext.getRequest();
    logger.info("{} >>> {}", request.getMethod(), request.getRequestURI().toString());
    String token = request.getParameter("token");
    if (token == null) {
        logger.error("Error! Request Token is Empty");
        currentContext.setSendZuulResponse(false);
        currentContext.setResponseStatusCode(401);
        try {
            currentContext.getResponse().getWriter().write("Request token is empty");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}
 
Example 4
Source File: TokenFilter.java    From springcloud_for_noob with MIT License 6 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();

    logger.info("--->>> TokenFilter {},{}", request.getMethod(), request.getRequestURL().toString());

    String token = request.getParameter("token");

    if (StringUtils.isNotBlank(token)) {
        ctx.setSendZuulResponse(true); //对请求进行路由
        ctx.setResponseStatusCode(200);
        ctx.set("isSuccess", true);
        return null;
    } else {
        ctx.setSendZuulResponse(false); //不对其进行路由
        ctx.setResponseStatusCode(400);
        ctx.setResponseBody("token is empty");
        ctx.set("isSuccess", false);
        return null;
    }
}
 
Example 5
Source File: AccessControlFilter.java    From flair-registry with Apache License 2.0 5 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
    if (ctx.getResponseBody() == null && !ctx.getResponseGZipped()) {
        ctx.setSendZuulResponse(false);
    }
    log.debug("Access Control: filtered unauthorized access on endpoint {}", ctx.getRequest().getRequestURI());
    return null;
}
 
Example 6
Source File: AccessFilter.java    From sanshanblog with Apache License 2.0 5 votes vote down vote up
/**
 * 网关抛异常
 *
 * @param body
 * @param code
 */
private void setFailedRequest(String body, int code) {
    log.debug("Reporting error ({}): {}", code, body);
    RequestContext ctx = RequestContext.getCurrentContext();
    ctx.setResponseStatusCode(code);
    if (ctx.getResponseBody() == null) {
        ctx.setResponseBody(body);
        ctx.setSendZuulResponse(false);
    }
}
 
Example 7
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 8
Source File: AccessControlFilter.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
    if (ctx.getResponseBody() == null && !ctx.getResponseGZipped()) {
        ctx.setSendZuulResponse(false);
    }
    log.debug("Access Control: filtered unauthorized access on endpoint {}", ctx.getRequest().getRequestURI());
    return null;
}
 
Example 9
Source File: AccessFilter.java    From SpringCloud-Shop with Apache License 2.0 5 votes vote down vote up
@Override public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    logger.info("send {} request to {}", request.getMethod(), request.getRequestURL().toString());

    /** 默认用户没有登录 */
    boolean flag = false;
    /** 获得请求的ServletPath */
    String servletPath = request.getServletPath();
    /**  判断请求是否需要拦截 */
    for (String s : IGNORE_URI) {
        if (servletPath.contains(s)) {
            flag = true;
            break;
        }
    }

    if(!flag){
        Object accessToken = request.getParameter("accessToken");
        // TODO accessToken 的获取及验证
        accessToken = "test";

        if(accessToken == null) {
            logger.warn("access token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            return null;
        }

        logger.info("accessToken ok");
        //路由转发
        ctx.setSendZuulResponse(true);
        ctx.setResponseStatusCode(200);
        return null;
    }else {
        return null;
    }
}
 
Example 10
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 11
Source File: GatewayFilter.java    From spring-cloud-microservice with MIT License 5 votes vote down vote up
/**
 * 过滤器的具体逻辑
 * 示例:是否包含token,没有则 401
 *
 * @return
 */
@Override
public Object run() {
    RequestContext context = RequestContext.getCurrentContext();
    HttpServletRequest request = context.getRequest();

    String token = request.getParameter("token");
    if (token == null || token.isEmpty()) {
        context.setSendZuulResponse(false);
        context.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
        context.setResponseBody("token invalid");
    }
    return null;
}
 
Example 12
Source File: _AccessControlFilter.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
    if (ctx.getResponseBody() == null) {
        ctx.setSendZuulResponse(false);
    }
    log.debug("Access Control: filtered unauthorized access on endpoint {}", ctx.getRequest().getRequestURI());
    return null;
}
 
Example 13
Source File: RateLimitingFilter.java    From tutorials with MIT License 5 votes vote down vote up
private void apiLimitExceeded() {
    RequestContext ctx = RequestContext.getCurrentContext();
    ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
    if (ctx.getResponseBody() == null) {
        ctx.setResponseBody("API rate limit exceeded");
        ctx.setSendZuulResponse(false);
    }
}
 
Example 14
Source File: AccessControlFilter.java    From e-commerce-microservice with Apache License 2.0 5 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
    ctx.setSendZuulResponse(false);
    log.debug("Access Control: filtered unauthorized access on endpoint {}", ctx.getRequest().getRequestURI());
    return null;
}
 
Example 15
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 16
Source File: PreviewFilter.java    From pig with MIT License 5 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    R<String> result = new R<>();
    result.setCode(479);
    result.setMsg("演示环境,没有权限操作");

    ctx.setResponseStatusCode(479);
    ctx.setSendZuulResponse(false);
    ctx.getResponse().setContentType("application/json;charset=UTF-8");
    ctx.setResponseBody(JSONObject.toJSONString(result));
    return null;
}
 
Example 17
Source File: AuthenticationAwareFilter.java    From ServiceComb-Company-WorkShop with Apache License 2.0 4 votes vote down vote up
private void rejectRequest(RequestContext context) {
  context.setResponseStatusCode(SC_FORBIDDEN);
  context.setSendZuulResponse(false);
}
 
Example 18
Source File: ScopesFilter.java    From heimdall with Apache License 2.0 4 votes vote down vote up
private void process() {
    final RequestContext context = RequestContext.getCurrentContext();

    final String client_id = context.getRequest().getHeader(CLIENT_ID);

    if (client_id != null) {

        App app = appRepository.findByClientId(client_id);
        if (app == null || app.getPlans() == null) return;

        Set<Long> apis = app.getPlans().stream().map(plan -> plan.getApi().getId()).collect(Collectors.toSet());
        Long apiId = (Long) context.get(API_ID);
        if (!apis.contains(apiId)) return;

        final Set<Long> allowedOperations = new HashSet<>();

        app.getPlans()
                .forEach(plan -> {
                    if (plan != null && plan.getApi().getId().equals(apiId))
                        plan.getScopes()
                                .forEach(scope -> {
                                    if (scope != null)
                                        allowedOperations.addAll(scope.getOperationsIds());
                                });
                });

        final Long operation = (Long) context.get(OPERATION_ID);

        if (operation == null) return;

        // If the allowedOperations is empty it means that Scopes are not set
        if (allowedOperations.isEmpty()) return;

        if (!allowedOperations.contains(operation)) {
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
            context.setResponseBody(HttpStatus.FORBIDDEN.getReasonPhrase());
            context.getResponse().setContentType(MediaType.TEXT_PLAIN_VALUE);
        }
    }
}
 
Example 19
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 20
Source File: PageRedirectionFilterTest.java    From api-layer with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void givenStatusCode302_whenShouldFilterCalled_thenPassFromFilter() {
    final RequestContext ctx = RequestContext.getCurrentContext();
    ctx.setResponseStatusCode(302);
    assertTrue(filter.shouldFilter());
}