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

The following examples show how to use com.netflix.zuul.context.RequestContext#setSendZuulResponse() . 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: LoginFilter.java    From leyou with Apache License 2.0 6 votes vote down vote up
@Override
public Object run() throws ZuulException {
    // 获取上下文
    RequestContext context = RequestContext.getCurrentContext();
    // 获取request
    HttpServletRequest request = context.getRequest();
    // 获取token
    String token = CookieUtils.getCookieValue(request, this.jwtProperties.getCookieName());
    // 校验
    try {
        // 校验通过什么都不做,即放行
        JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey());
    } catch (Exception e) {
        // 校验出现异常,返回403
        context.setSendZuulResponse(false);
        context.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
    }
    return null;
}
 
Example 2
Source File: MyFilter.java    From softservice with MIT License 6 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
    Object accessToken = request.getParameter("token");
    if(accessToken == null) {
        log.warn("token is empty");
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(401);
        try {
            ctx.getResponse().getWriter().write("token is empty");
        }catch (Exception e){}

        return null;
    }
    log.info("ok");
    return null;
}
 
Example 3
Source File: ValidateCodeFilter.java    From pig with MIT License 6 votes vote down vote up
@Override
public Object run() {
    try {
        checkCode(RequestContext.getCurrentContext().getRequest());
    } catch (ValidateCodeException e) {
        RequestContext ctx = RequestContext.getCurrentContext();
        R<String> result = new R<>(e);
        result.setCode(478);

        ctx.setResponseStatusCode(478);
        ctx.setSendZuulResponse(false);
        ctx.getResponse().setContentType("application/json;charset=UTF-8");
        ctx.setResponseBody(JSONObject.toJSONString(result));
    }
    return null;
}
 
Example 4
Source File: AuthFilter.java    From springcloud-course with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object run() throws ZuulException {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    log.info(String.format("header-token:%s,param-token:%s", request.getHeader("token"), request.getParameter("token")));
    String token_header = request.getHeader("token") == null ? "" : request.getHeader("token");
    String token_param = request.getParameter("token") == null ? "" : request.getParameter("token");
    if (token_header.equals("") && token_param.equals("")) {
        try {
            ctx.setSendZuulResponse(false);
            ctx.getResponse().getWriter().write("{\"code\": 9999,\"message\": \"token is empty.\"}");
        } catch (Exception e) {
            log.warning("system error");
        }

    } else if (!token_header.equals("")) {
        log.info(String.format("token is %s", token_header));
    } else if (!token_param.equals("")) {
        log.info(String.format("token is %s", token_param));
    }
    return null;
}
 
Example 5
Source File: AuthFilter.java    From springcloud-course with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object run() throws ZuulException {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    log.info(String.format("header-token:%s,param-token:%s", request.getHeader("token"), request.getParameter("token")));
    String token_header = request.getHeader("token") == null ? "" : request.getHeader("token");
    String token_param = request.getParameter("token") == null ? "" : request.getParameter("token");
    if (token_header.equals("") && token_param.equals("")) {
        try {
            ctx.setSendZuulResponse(false);
            ctx.getResponse().getWriter().write("{\"code\": 9999,\"message\": \"token is empty.\"}");
        } catch (Exception e) {
            log.warning("system error");
        }

    } else if (!token_header.equals("")) {
        log.warning(String.format("token is %s", token_header));
    } else if (!token_param.equals("")) {
        log.warning(String.format("token is %s", token_param));
    }
    return null;
}
 
Example 6
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 7
Source File: RateLimitingFilter.java    From cubeai with Apache License 2.0 5 votes vote down vote up
/**
 * Create a Zuul response error when the API limit is exceeded.
 */
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 8
Source File: PreFilter.java    From NetworkDisk_Storage with GNU General Public License v2.0 5 votes vote down vote up
private void verifyToken(RequestContext ctx) {
    try {
        String token = CookieUtils.getCookie("token");
        Claims claims = JWTUtils.parseJWT(token, "nimadetou".getBytes());
        String subject = claims.getSubject();
        UserInfoDTO userinfo = JSONUtils.parseObject(subject, UserInfoDTO.class);
        log.info(userinfo.getUserId());
        ctx.setSendZuulResponse(true);
    } catch (Exception e) {
        ctx.setSendZuulResponse(false);
    }
}
 
Example 9
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 10
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 11
Source File: RateLimitFilter.java    From springcloud-course with GNU General Public License v3.0 5 votes vote down vote up
@Override
    public Object run() throws ZuulException {
        try {
            RequestContext ctx = RequestContext.getCurrentContext();
            HttpServletRequest request = ctx.getRequest();
            log.info(request.getRequestURI());
            HttpServletResponse response = ctx.getResponse();
            if (!rateLimiter.tryAcquire()) {
//                HttpStatus httpStatus = HttpStatus.TOO_MANY_REQUESTS;
//                response.setContentType(MediaType.TEXT_PLAIN_VALUE);
//                response.setStatus(httpStatus.value());
//                response.getWriter().append(httpStatus.getReasonPhrase());
//                ctx.setSendZuulResponse(false);
//                throw new ZuulException(
//                        httpStatus.getReasonPhrase(),
//                        httpStatus.value(),
//                        httpStatus.getReasonPhrase()
//                );
                ctx.setSendZuulResponse(false);
                response.setStatus(200);
                response.getWriter().write("{\"code\": 99999,\"message\": \"too many requests.\"}");
            }
        } catch (Exception e) {
            log.warning(e.getMessage());
            ReflectionUtils.rethrowRuntimeException(e);
        }
        return null;
    }
 
Example 12
Source File: CacheFetchFilter.java    From ServiceComb-Company-WorkShop with Apache License 2.0 5 votes vote down vote up
private void returnResultWithoutForwardingToZuul(
    RequestContext context,
    String body,
    String contentType) {
  context.setResponseStatusCode(SC_OK);
  context.getResponse().setHeader(CONTENT_TYPE, contentType);
  context.setResponseBody(body);
  context.setSendZuulResponse(false);
}
 
Example 13
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 14
Source File: CORSInterceptorService.java    From heimdall with Apache License 2.0 5 votes vote down vote up
public void executeCorsPreFilter(Map<String, String> cors) {
    RequestContext ctx = RequestContext.getCurrentContext();

    if (ctx.getRequest().getMethod().equals(HttpMethod.OPTIONS.name())) {
        addHeadersToResponseOptions(cors);
        ctx.setSendZuulResponse(false);
        ctx.getResponse().setStatus(HttpStatus.OK.value());
    } else {
        ctx.set(ConstantsContext.CORS_FILTER, cors);
    }
}
 
Example 15
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 16
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 17
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());
    ctx.setSendZuulResponse(false);
    log.debug("Access Control: filtered unauthorized access on endpoint {}", ctx.getRequest().getRequestURI());
    return null;
}
 
Example 18
Source File: InternalURIAccessFilter.java    From cloud-service with MIT License 5 votes vote down vote up
@Override
public Object run() {
	RequestContext requestContext = RequestContext.getCurrentContext();
	requestContext.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
	requestContext.setResponseBody(HttpStatus.FORBIDDEN.getReasonPhrase());
	requestContext.setSendZuulResponse(false);

	return null;
}
 
Example 19
Source File: BlackIPAccessFilter.java    From cloud-service with MIT License 5 votes vote down vote up
@Override
public Object run() {
	RequestContext requestContext = RequestContext.getCurrentContext();
	requestContext.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
	requestContext.setResponseBody("black ip");
	requestContext.setSendZuulResponse(false);

	return null;
}
 
Example 20
Source File: RequestLimitFilter.java    From oneplatform with Apache License 2.0 4 votes vote down vote up
@Override
public Object run() {
	RequestContext ctx = RequestContext.getCurrentContext();
       try {
   		HttpServletRequest request = ctx.getRequest();
   		
   		if(postOnly && !HttpMethod.POST.name().equalsIgnoreCase(request.getMethod())){
   			return null;
   		}
   		
   		if(HttpMethod.OPTIONS.name().equalsIgnoreCase(request.getMethod()) || HttpMethod.HEAD.name().equalsIgnoreCase(request.getMethod())){
   			return null;
   		}
   		
   		if(gloabalLimiter != null){
   			//limiter.acquire();
   			if(!gloabalLimiter.tryAcquire(1, TimeUnit.SECONDS)){
   				ctx.setSendZuulResponse(false);
   				ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
   				ctx.setResponseBody(MSG_TOO_MANY_REQUESTS);
   				return null;
   			}
   		}
   		

   		//后台系统不限制
   		if(perLimiter != null){
   			UserSession session = SecurityDelegating.getCurrentSession();
   			if(!perLimiter.tryAcquire(request,session.getSessionId())){
   				ctx.setSendZuulResponse(false);
   				ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
   				ctx.setResponseBody(MSG_REQUEST_TOO_FAST);
   				return null;
   			}
   		}
	} catch (Exception e) {
		String error = "Error during filtering[RequestLimitFilter]";
		log.error(error,e);
		WebUtils.responseOutJson(ctx.getResponse(), JsonUtils.toJson(new WrapperResponse<>(500, error)));
	}
	return null;
}