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

The following examples show how to use com.netflix.zuul.context.RequestContext#getRequest() . 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 boolean shouldFilter() {
    // 获取上下文
    RequestContext ctx = RequestContext.getCurrentContext();
    // 获取request
    HttpServletRequest req = ctx.getRequest();
    // 获取路径
    String requestURI = req.getRequestURI();
    // 判断白名单
    // 遍历允许访问的路径
    for (String path : this.filterProperties.getAllowPaths()) {
        // 然后判断是否是符合
        if (requestURI.startsWith(path)) {
            return false;
        }
    }
    return true;
}
 
Example 2
Source File: AccessFilter.java    From xxproject with Apache License 2.0 6 votes vote down vote up
@Override
    public Object run() {
    	LOGGER.info("==============================================");
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        LOGGER.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));
//        Object accessToken = request.getParameter("accessToken");
//        if(accessToken == null) {
//        	LOGGER.warn("access token is empty");
//            ctx.setSendZuulResponse(false);
//            ctx.setResponseStatusCode(401);
//            return null;
//        }
//        LOGGER.info("access token ok");
        String authString = request.getHeader("Authorization");
        LOGGER.info("authString: {}", authString);
        LOGGER.info("==============================================");
        return null;
    }
 
Example 3
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 4
Source File: UserInfoHeaderFilter.java    From Taroco with Apache License 2.0 6 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        RequestContext requestContext = RequestContext.getCurrentContext();
        requestContext.addZuulRequestHeader(SecurityConstants.USER_HEADER, authentication.getName());
        requestContext.addZuulRequestHeader(SecurityConstants.USER_ROLE_HEADER, CollUtil.join(authentication.getAuthorities(), ","));
        String tokenValue = extractToken(request);
        if (!StringUtils.isEmpty(tokenValue)) {
            OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
            if (accessToken != null && !CollectionUtils.isEmpty(accessToken.getAdditionalInformation())) {
                Map<String, Object> information = accessToken.getAdditionalInformation();
                requestContext.addZuulRequestHeader(SecurityConstants.HEADER_LABEL, information.get(SecurityConstants.HEADER_LABEL) + "");
                requestContext.addZuulRequestHeader(SecurityConstants.USER_PERMISSION_HEADER, information.get(SecurityConstants.USER_PERMISSION_HEADER) + "");
            }
        }
    }
    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.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 6
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 7
Source File: TokenFilter.java    From spring-boot-demo with MIT License 6 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();

    log.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 8
Source File: BaseFilter.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
private String getUri() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    String uri = request.getRequestURI();
    uri = StrUtil.subSuf(uri, zuulPrefix.length());
    uri = StrUtil.subSuf(uri, uri.indexOf("/", 1));
    return uri;
}
 
Example 9
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 10
Source File: InternalURIAccessFilter.java    From cloud-service with MIT License 5 votes vote down vote up
@Override
public boolean shouldFilter() {
	RequestContext requestContext = RequestContext.getCurrentContext();
	HttpServletRequest request = requestContext.getRequest();

	return PatternMatchUtils.simpleMatch("*-anon/internal*", request.getRequestURI());
}
 
Example 11
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;
}
 
Example 12
Source File: PreRequestLogFilter.java    From spring-cloud-docker-microservice-book-code with Apache License 2.0 5 votes vote down vote up
@Override
public Object run() {
  RequestContext ctx = RequestContext.getCurrentContext();
  HttpServletRequest request = ctx.getRequest();
  PreRequestLogFilter.LOGGER.info(String.format("send %s request to %s", request.getMethod(), request.getRequestURL().toString()));
  return null;
}
 
Example 13
Source File: AuthSellerFilter.java    From code with Apache License 2.0 5 votes vote down vote up
@Override
public boolean shouldFilter() {
    RequestContext requestContext = RequestContext.getCurrentContext();
    HttpServletRequest request = requestContext.getRequest();
    if ("/order/order/finish".equals(request.getRequestURI())) {
        return true;
    }
    return false;
}
 
Example 14
Source File: SimpleLoggingFilter.java    From Mastering-Spring-5.0 with MIT License 5 votes vote down vote up
@Override
public Object run() {
  RequestContext context = RequestContext.getCurrentContext();
  HttpServletRequest httpRequest = context.getRequest();

  log.info(String.format("Request Method : %s \n URL:  %s", httpRequest.getMethod(), httpRequest.getRequestURL().toString()));

  return null;
}
 
Example 15
Source File: LoggingFilter.java    From cxf-spring-cloud-netflix-docker with MIT License 5 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();

    LOG.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));

    return null;
}
 
Example 16
Source File: CustomPreZuulFilter.java    From spring-security-oauth with MIT License 5 votes vote down vote up
@Override
public Object run() {
    final RequestContext ctx = RequestContext.getCurrentContext();
    logger.info("in zuul filter " + ctx.getRequest().getRequestURI());
    byte[] encoded;
    try {
        encoded = Base64.getEncoder().encode("fooClientIdPassword:secret".getBytes("UTF-8"));
        ctx.addZuulRequestHeader("Authorization", "Basic " + new String(encoded));
        logger.info("pre filter");
        logger.info(ctx.getRequest().getHeader("Authorization"));

        final HttpServletRequest req = ctx.getRequest();

        final String refreshToken = extractRefreshToken(req);
        if (refreshToken != null) {
            final Map<String, String[]> param = new HashMap<String, String[]>();
            param.put("refresh_token", new String[] { refreshToken });
            param.put("grant_type", new String[] { "refresh_token" });

            ctx.setRequest(new CustomHttpServletRequest(req, param));
        }

    } catch (final UnsupportedEncodingException e) {
        logger.error("Error occured in pre filter", e);
    }

    //

    return null;
}
 
Example 17
Source File: TokenFilter.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Override
    public Object run() {

//        int i=10/0;

        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info("我是TokenFilter");
        String token = request.getHeader("token");// 获取请求的参数

        // 如果有token参数并且token值为123456,才进行路由
        if (StringUtils.isNotBlank(token) && token.equals("123456")) {
            ctx.setSendZuulResponse(true); //对请求进行路由
            ctx.setResponseStatusCode(200);
            ctx.set("code", 1);
        } else {
            //失败之后通知后续不应该执行了
            ctx.set("isShould",false);

            ctx.setSendZuulResponse(false); //不对其进行路由
            ctx.setResponseStatusCode(401);
            HttpServletResponse response = ctx.getResponse();
            response.setHeader("content-type", "text/html;charset=utf8");
            ctx.setResponseBody("认证失败");
            ctx.set("code", 0);
        }
        return null;
    }
 
Example 18
Source File: AuthenticationFilter.java    From DBus with Apache License 2.0 5 votes vote down vote up
@Override
public boolean shouldFilter() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    return !request.getRequestURI().endsWith("/users/create")
            && !request.getRequestURI().endsWith("/configCenter/isInitialized")
            && !request.getRequestURI().endsWith("/configCenter/getBasicConf")
            && !request.getRequestURI().endsWith("/configCenter/updateBasicConf")
            && !request.getRequestURI().endsWith("/accessDbusPreTreated/check/1")
            && !request.getRequestURI().endsWith("/accessDbusPreTreated/downloadExcleModel");

}
 
Example 19
Source File: RateLimitPostFilter.java    From spring-cloud-zuul-ratelimit with Apache License 2.0 4 votes vote down vote up
private Long getRequestStartTime() {
    final RequestContext ctx = RequestContext.getCurrentContext();
    final HttpServletRequest request = ctx.getRequest();
    return (Long) request.getAttribute(REQUEST_START_TIME);
}
 
Example 20
Source File: SecondFilter.java    From micro-service with Apache License 2.0 4 votes vote down vote up
@Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        //HttpServletResponse response = ctx.getResponse();
        
        log.info("第二级过滤器!");
        
        log.info("===============");
        

        throw new RuntimeException();


//        log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));
//        System.out.println(request.getRequestURL());

    }