com.netflix.zuul.context.RequestContext Java Examples

The following examples show how to use com.netflix.zuul.context.RequestContext. 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: _SwaggerBasePathRewritingFilter.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 7 votes vote down vote up
private String rewriteBasePath(RequestContext context) {
    InputStream responseDataStream = context.getResponseDataStream();
    String requestUri = RequestContext.getCurrentContext().getRequest().getRequestURI();
    try {
        String response = CharStreams.toString(new InputStreamReader(responseDataStream));
        if (response != null) {
            LinkedHashMap<String, Object> map = this.mapper.readValue(response, LinkedHashMap.class);

            String basePath = requestUri.replace(Swagger2Controller.DEFAULT_URL,"");
            map.put("basePath",basePath);
            log.debug("Swagger-docs: rewritten Base URL with correct micro-service route: {}", basePath);
            return mapper.writeValueAsString(map);
        }
    }
    catch (IOException e){
        log.error("Swagger-docs filter error", e);
    }
    return null;
}
 
Example #2
Source File: SwaggerBasePathRewritingFilter.java    From flair-registry with Apache License 2.0 7 votes vote down vote up
@Override
public Object run() {
    RequestContext context = RequestContext.getCurrentContext();

    context.getResponse().setCharacterEncoding("UTF-8");

    String rewrittenResponse = rewriteBasePath(context);
    if (context.getResponseGZipped()) {
        try {
            context.setResponseDataStream(new ByteArrayInputStream(gzipData(rewrittenResponse)));
        } catch (IOException e) {
            log.error("Swagger-docs filter error", e);
        }
    } else {
        context.setResponseBody(rewrittenResponse);
    }
    return null;
}
 
Example #3
Source File: _AccessControlFilter.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Filter requests on endpoints that are not in the list of authorized microservices endpoints.
 */
@Override
public boolean shouldFilter() {
    String requestUri = RequestContext.getCurrentContext().getRequest().getRequestURI();

    // If the request Uri does not start with the path of the authorized endpoints, we block the request
    for (Route route : routeLocator.getRoutes()) {
        String serviceUrl = route.getFullPath();
        String serviceName = route.getId();

        // If this route correspond to the current request URI
        // We do a substring to remove the "**" at the end of the route URL
        if (requestUri.startsWith(serviceUrl.substring(0, serviceUrl.length() - 2))) {
            if (isAuthorizedRequest(serviceUrl, serviceName, requestUri)) {
                return false;
            }
        }
    }
    return true;
}
 
Example #4
Source File: AccessControlFilter.java    From e-commerce-microservice with Apache License 2.0 6 votes vote down vote up
/**
 * Filter requests on endpoints that are not in the list of authorized microservices endpoints.
 */
@Override
public boolean shouldFilter() {
    String requestUri = RequestContext.getCurrentContext().getRequest().getRequestURI();
    String contextPath = RequestContext.getCurrentContext().getRequest().getContextPath();

    // If the request Uri does not start with the path of the authorized endpoints, we block the request
    for (Route route : routeLocator.getRoutes()) {
        String serviceUrl = contextPath + route.getFullPath();
        String serviceName = route.getId();

        // If this route correspond to the current request URI
        // We do a substring to remove the "**" at the end of the route URL
        if (requestUri.startsWith(serviceUrl.substring(0, serviceUrl.length() - 2))) {
return !isAuthorizedRequest(serviceUrl, serviceName, requestUri);
        }
    }
    return true;
}
 
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: AbstractRateLimitFilter.java    From spring-cloud-zuul-ratelimit with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected List<Policy> policy(Route route, HttpServletRequest request) {
    List<Policy> policies = (List<Policy>) RequestContext.getCurrentContext().get(CURRENT_REQUEST_POLICY);
    if (policies != null) {
        return policies;
    }

    String routeId = route != null ? route.getId() : null;

    RequestContext.getCurrentContext().put(ALREADY_LIMITED, false);

    policies = properties.getPolicies(routeId).stream()
            .filter(policy -> applyPolicy(request, route, policy))
            .collect(Collectors.toList());

    addObjectToCurrentRequestContext(CURRENT_REQUEST_POLICY, policies);

    return policies;
}
 
Example #7
Source File: GreetingsClientApplication.java    From building-microservices with Apache License 2.0 6 votes vote down vote up
@Override
public Object run() {
    try {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse response = currentContext.getResponse();

        if (!this.rateLimiter.tryAcquire()) {
            response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
            response.getWriter().append(HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase());
            currentContext.setSendZuulResponse(false);
        }
    } catch (IOException e) {
        ReflectionUtils.rethrowRuntimeException(e);
    }
    return null;
}
 
Example #8
Source File: SwaggerBasePathRewritingFilterTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void run_on_valid_response_gzip() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
    RequestContext context = RequestContext.getCurrentContext();
    context.setRequest(request);

    MockHttpServletResponse response = new MockHttpServletResponse();
    context.setResponseGZipped(true);
    context.setResponse(response);

    context.setResponseDataStream(new ByteArrayInputStream(gzipData("{\"basePath\":\"/\"}")));

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());

    InputStream responseDataStream = new GZIPInputStream(context.getResponseDataStream());
    String responseBody = IOUtils.toString(responseDataStream, StandardCharsets.UTF_8);
    assertEquals("{\"basePath\":\"/service1\"}", responseBody);
}
 
Example #9
Source File: SwaggerBasePathRewritingFilterTest.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void run_on_valid_response_gzip() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
    RequestContext context = RequestContext.getCurrentContext();
    context.setRequest(request);

    MockHttpServletResponse response = new MockHttpServletResponse();
    context.setResponseGZipped(true);
    context.setResponse(response);

    context.setResponseDataStream(new ByteArrayInputStream(gzipData("{\"basePath\":\"/\"}")));

    filter.run();

    assertEquals("UTF-8", response.getCharacterEncoding());

    InputStream responseDataStream = new GZIPInputStream(context.getResponseDataStream());
    String responseBody = IOUtils.toString(responseDataStream, StandardCharsets.UTF_8);
    assertEquals("{\"basePath\":\"/service1\"}", responseBody);
}
 
Example #10
Source File: BaseFilter.java    From convergent-ui with Apache License 2.0 6 votes vote down vote up
protected void writeResponse(String responseBody, MimeType contentType) throws Exception {
    RequestContext context = RequestContext.getCurrentContext();
    // there is no body to send
    if (responseBody == null || responseBody.isEmpty()) {
        return;
    }
    HttpServletResponse servletResponse = context.getResponse();
    servletResponse.setCharacterEncoding("UTF-8");
    servletResponse.setContentType(contentType.toString());
    OutputStream outStream = servletResponse.getOutputStream();
    InputStream is = null;
    try {
        writeResponse(new ByteArrayInputStream(responseBody.getBytes()), outStream);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            outStream.flush();
            outStream.close();
        } catch (IOException ex) {
        }
    }
}
 
Example #11
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 #12
Source File: SwaggerBasePathRewritingFilterTest.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
@Test
public void run_on_valid_response() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
    RequestContext context = RequestContext.getCurrentContext();
    context.setRequest(request);

    MockHttpServletResponse response = new MockHttpServletResponse();
    context.setResponseGZipped(false);
    context.setResponse(response);

    InputStream in = IOUtils.toInputStream("{\"basePath\":\"/\"}", StandardCharsets.UTF_8);
    context.setResponseDataStream(in);

    filter.run();

    assertThat(response.getCharacterEncoding()).isEqualTo("UTF-8");
    assertThat(context.getResponseBody()).isEqualTo("{\"basePath\":\"/service1\"}");
}
 
Example #13
Source File: ErrorFilter.java    From micro-service with Apache License 2.0 6 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("===============");
        
//        log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));
//        System.out.println(request.getRequestURL());
        
//        Object accessToken = request.getParameter("accessToken");
//        if(accessToken == null) {
//            log.warn("access token is empty");
//            ctx.setSendZuulResponse(false);
//            ctx.setResponseStatusCode(401);
//            return null;
//        }
//        log.info("access token ok");
        return null;
    }
 
Example #14
Source File: ZosmfScheme.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void applyToRequest(HttpRequest request) {
    Cookies cookies = Cookies.of(request);
    final RequestContext context = RequestContext.getCurrentContext();

    Optional<String> jwtToken = authenticationService.getJwtTokenFromRequest(context.getRequest());
    jwtToken.ifPresent(token -> {
        // parse JWT token to detect the source (z/OSMF / Zowe)
        QueryResponse queryResponse = authenticationService.parseJwtToken(token);
        switch (queryResponse.getSource()) {
            case ZOSMF:
                cookies.remove(authConfigurationProperties.getCookieProperties().getCookieName());
                createCookie(cookies, ZosmfService.TokenType.JWT.getCookieName(), token);
                break;
            case ZOWE:
                final String ltpaToken = authenticationService.getLtpaTokenWithValidation(token);
                createCookie(cookies, ZosmfService.TokenType.LTPA.getCookieName(), ltpaToken);
                break;
            default:
                return;
        }
        // remove authentication part
        request.removeHeaders(HttpHeaders.AUTHORIZATION);
    });
}
 
Example #15
Source File: FirstFilter.java    From micro-service with Apache License 2.0 6 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("===============");

//        log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));
//        System.out.println(request.getRequestURL());
        
//        Object accessToken = request.getParameter("accessToken");
//        if(accessToken == null) {
//            log.warn("access token is empty");
//            ctx.setSendZuulResponse(false);
//            ctx.setResponseStatusCode(401);
//            return null;
//        }
//        log.info("access token ok");
        return null;
    }
 
Example #16
Source File: RequestHelper.java    From heimdall with Apache License 2.0 6 votes vote down vote up
/**
    * Tries to create a {@link RequestResponseParser} from the current context.
    * If it fail, returns a new {@link RequestResponseParser}.
    * 
    * @return {@link RequestResponseParser}
    */
   public RequestResponseParser dumpRequest() {
        RequestContext ctx = RequestContext.getCurrentContext();
        RequestResponseParser reqDTO = new RequestResponseParser();
        HttpServletRequest request = ctx.getRequest();
        
        try {
             reqDTO.setHeaders(getRequestHeadersInfo(request));
             reqDTO.setBody(StreamUtils.copyToString(request.getInputStream(), Charset.forName("UTF-8")));
             reqDTO.setUri(UrlUtil.getCurrentUrl(request));
} catch (IOException e) {
     log.error(e.getMessage(), e);
	return new RequestResponseParser(); 
}
        
        return reqDTO;
   }
 
Example #17
Source File: SwaggerBasePathRewritingFilter.java    From e-commerce-microservice with Apache License 2.0 6 votes vote down vote up
@Override
public Object run() {
    RequestContext context = RequestContext.getCurrentContext();

    context.getResponse().setCharacterEncoding("UTF-8");

    String rewrittenResponse = rewriteBasePath(context);
    if (context.getResponseGZipped()) {
        try {
            context.setResponseDataStream(new ByteArrayInputStream(gzipData(rewrittenResponse)));
        } catch (IOException e) {
            log.error("Swagger-docs filter error", e);
        }
    } else {
        context.setResponseBody(rewrittenResponse);
    }
    return null;
}
 
Example #18
Source File: RateLimitingFilter.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object run() {
    String id = getId(RequestContext.getCurrentContext().getRequest());
    Date date = getPeriod();

    // check current rate limit
    // default limit per user is 100,000 API calls per hour
    Long count = rateLimitingRepository.getCounter(id, TIME_PERIOD, date);
    log.debug("Rate limiting for user {} at {} - {}",  id, date, count);
    if (count > rateLimit) {
        apiLimitExceeded();
    } else {
        // count calls per hour
        rateLimitingRepository.incrementCounter(id, TIME_PERIOD, date);
    }
    return null;
}
 
Example #19
Source File: SlashFilterTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void proxyIsNull() throws Exception {
    final RequestContext ctx = RequestContext.getCurrentContext();
    ctx.set(PROXY_KEY, null);
    this.filter.run();
    Boolean isLocation = false;
    List<Pair<String, String>> zuulResponseHeaders = ctx.getZuulResponseHeaders();
    if (zuulResponseHeaders != null) {
        for (Pair<String, String> header : zuulResponseHeaders) {
            if (header.first().equals("Location"))
                isLocation = true;
        }
    }
    assertEquals(false, isLocation);
    assertEquals(500, ctx.getResponseStatusCode());
}
 
Example #20
Source File: AccessFilter.java    From pig with MIT License 6 votes vote down vote up
@Override
public Object run() {
    RequestContext requestContext = RequestContext.getCurrentContext();
    String version = requestContext.getRequest().getHeader(SecurityConstants.VERSION);
    if (canary && StrUtil.isNotBlank(version)) {
        RibbonVersionHolder.setContext(version);
    }

    requestContext.set("startTime", System.currentTimeMillis());
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        requestContext.addZuulRequestHeader(SecurityConstants.USER_HEADER, authentication.getName());
        requestContext.addZuulRequestHeader(SecurityConstants.ROLE_HEADER, CollectionUtil.join(authentication.getAuthorities(), ","));
    }
    return null;
}
 
Example #21
Source File: RateLimitPreFilterTest.java    From spring-cloud-zuul-ratelimit with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setUp() {
    MockitoAnnotations.initMocks(this);
    CounterFactory.initialize(new EmptyCounterFactory());

    when(httpServletRequest.getContextPath()).thenReturn("");
    when(httpServletRequest.getRequestURI()).thenReturn("/servicea/test");
    when(httpServletRequest.getRemoteAddr()).thenReturn("127.0.0.1");
    RequestContext requestContext = new RequestContext();
    requestContext.setRequest(httpServletRequest);
    requestContext.setResponse(httpServletResponse);
    RequestContext.testSetCurrentContext(requestContext);
    RequestContextHolder.setRequestAttributes(requestAttributes);
    rateLimitProperties = new RateLimitProperties();
    rateLimitProperties.setAddResponseHeaders(false);
    UrlPathHelper urlPathHelper = new UrlPathHelper();
    RateLimitUtils rateLimitUtils = new DefaultRateLimitUtils(rateLimitProperties);
    Route route = new Route("servicea", "/test", "servicea", "/servicea", null, Collections.emptySet());
    TestRouteLocator routeLocator = new TestRouteLocator(Collections.emptyList(), Lists.newArrayList(route));
    target = new RateLimitPreFilter(rateLimitProperties, routeLocator, urlPathHelper, rateLimiter, rateLimitKeyGenerator, rateLimitUtils, eventPublisher);
}
 
Example #22
Source File: AccessControlFilter.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Filter requests on endpoints that are not in the list of authorized microservices endpoints.
 */
@Override
public boolean shouldFilter() {
    String requestUri = RequestContext.getCurrentContext().getRequest().getRequestURI();

    // If the request Uri does not start with the path of the authorized endpoints, we block the request
    for (Route route : routeLocator.getRoutes()) {
        String serviceUrl = route.getFullPath();
        String serviceName = route.getId();

        // If this route correspond to the current request URI
        // We do a substring to remove the "**" at the end of the route URL
        if (requestUri.startsWith(serviceUrl.substring(0, serviceUrl.length() - 2))) {
            if (isAuthorizedRequest(serviceUrl, serviceName, requestUri)) {
                return false;
            }
        }
    }
    return true;
}
 
Example #23
Source File: ServiceAuthenticationFilterTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void givenValidJwt_whenTokenRequired_thenRejected() {
    String jwtToken = "validJwtToken";
    AuthenticationCommand cmd = createJwtValidationCommand(jwtToken);
    doReturn(TokenAuthentication.createAuthenticated("user", jwtToken)).when(authenticationService).validateJwtToken(jwtToken);

    serviceAuthenticationFilter.run();

    verify(RequestContext.getCurrentContext(), never()).setSendZuulResponse(anyBoolean());
    verify(RequestContext.getCurrentContext(), never()).setResponseStatusCode(anyInt());
    verify(cmd, times(1)).apply(null);
}
 
Example #24
Source File: AccessControlFilter.java    From jhipster-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 #25
Source File: SentinelZuulPreFilter.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private Set<String> pickMatchingApiDefinitions(RequestContext requestContext) {
    Set<String> apis = new HashSet<>();
    for (RequestContextApiMatcher matcher : ZuulGatewayApiMatcherManager.getApiMatcherMap().values()) {
        if (matcher.test(requestContext)) {
            apis.add(matcher.getApiName());
        }
    }
    return apis;
}
 
Example #26
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 #27
Source File: SwaggerBasePathRewritingFilterTest.java    From e-commerce-microservice with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotFilter_on_wrong_url() {

    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/management/info");
    RequestContext.getCurrentContext().setRequest(request);

    assertFalse(filter.shouldFilter());
}
 
Example #28
Source File: SwaggerBasePathRewritingFilterTest.java    From cubeai with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotFilter_on_wrong_url() {

    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/management/info");
    RequestContext.getCurrentContext().setRequest(request);

    assertFalse(filter.shouldFilter());
}
 
Example #29
Source File: TokenRelayFilter.java    From e-commerce-microservice with Apache License 2.0 5 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    @SuppressWarnings("unchecked")
    Set<String> headers = (Set<String>) ctx.get("ignoredHeaders");
    // JWT tokens should be relayed to the resource servers
    headers.remove("authorization");
    return null;
}
 
Example #30
Source File: DebugHeaderFilter.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object run() {
    String debug = convertToPrettyPrintString(Debug.getRoutingDebug());
    log.debug("Filter Debug Info = \n{}", debug);
    log.debug("RibbonRetryDebug: " + RequestContextUtils.getDebugInfo());
    RequestContext.getCurrentContext().addZuulResponseHeader(
        "ZuulFilterDebug", Debug.getRoutingDebug().stream().collect(Collectors.joining("|")));
    RequestContext.getCurrentContext().addZuulResponseHeader(
        "RibbonRetryDebug", RequestContextUtils.getDebugInfo());
    return null;
}