/*
   * (non-Javadoc)
   *
   * @see
   * com.sun.jersey.spi.container.ContainerRequestFilter#filter(com.sun.jersey
   * .spi.container.ContainerRequest)
   */
  @Override
  public ContainerRequest filter(ContainerRequest request) {
    if (!initDone) {
      init();
    }
    if (logStdOut) {
      String path = request.getRequestUri().getPath();

      // mediaType=multipart/form-data;boundary=----WebKitFormBoundaryTHan76r5AkgpAuVG
      if (request.getMediaType() != null) {
        // logger.info("DELETE ME: mediaType=" + request.getMediaType()
        // + ", getType()" + request.getMediaType().getType()
        // + ", getSubType()="
        // + request.getMediaType().getSubtype());
      } else {
        logger.info("DELETE ME: mediaType is null. path=" + path);
      }
      if ((request.getMediaType() == null || !request.getMediaType().getType().equals("multipart"))
          && !path.endsWith("/service/general/logs")) {
        try {
          request = super.filter(request);
        } catch (Throwable t) {
          logger.error("Error FILTER logging. path=" + path, t);
        }
      }
    }

    return request;
  }
 @Override
 public ContainerRequest filter(final ContainerRequest request) {
   if (this.forceSSL && (!request.isSecure())) {
     throw new PermanentRedirectException(
         UriBuilder.fromUri(request.getRequestUri()).scheme("https").build());
   }
   return request;
 }
示例#3
0
 @Override
 public ContainerRequest filter(ContainerRequest containerRequest) {
   try {
     // Calling setURIs method clears the cached method, path etc.
     containerRequest.setUris(
         containerRequest.getBaseUri(),
         new URI(containerRequest.getRequestUri().toString().replace("/ws/", "/")));
   } catch (URISyntaxException e) {
     e.printStackTrace();
   }
   return containerRequest;
 }
示例#4
0
    public ContainerRequest filter(ContainerRequest request) {
      log.debug("Url invoked is: " + uriInfo.getPath());

      // We need to let the caller get through to the authentication call
      if (uriInfo.getPath() != null
          && (uriInfo.getPath().equalsIgnoreCase("security-resource/authenticate")
              || uriInfo.getPath().startsWith("records")
              || uriInfo.getPath().startsWith("record-links")
              || uriInfo.getPath().startsWith("entities")
              || uriInfo.getPath().startsWith("entity-attributes")
              || uriInfo.getPath().startsWith("identifier-domains")
              || uriInfo.getPath().equalsIgnoreCase("application.wadl"))) {
        log.debug("Request permitted due to URI being present in the exclusion list.");
        return request;
      }

      String sessionKey = request.getHeaderValue(OPENEMPI_SESSION_KEY_HEADER);
      if (sessionKey != null && sessionKey.length() > 0) {
        User user = org.openhie.openempi.context.Context.authenticate(sessionKey);
        if (user == null) {
          throw new WebApplicationException(Response.Status.UNAUTHORIZED);
        }
        return request;
      }
      throw new WebApplicationException(Response.Status.UNAUTHORIZED);
    }
 @Override
 public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
   String version = request.getHeaderValue("Version");
   if (!supportedVersions.contains(version)) {
     response.setStatus(301);
     response.setEntity(null);
   }
   return response;
 }
  @Override
  public ContainerRequest filter(final ContainerRequest request) {
    if (log.isDebugEnabled()) {
      log.debug("request.getAbsolutePath : " + request.getAbsolutePath());
      log.debug("request.getBaseUri : " + request.getBaseUri());
    }

    RequestContext.clearRequestContext();

    RequestContext ctx =
        new RequestContext(
            UriBuilder.fromUri(request.getBaseUri()),
            request.getHeaderValue(RequestContext.HATEOAS_OPTIONS_HEADER));

    RequestContext.setRequestContext(ctx);

    return request;
  }
 @Override
 public ContainerResponse filter(
     final ContainerRequest request, final ContainerResponse response) {
   if (request.isSecure()) {
     final String value = String.format("max-age=%s; includeSubDomains", EXPIRY);
     response.getHttpHeaders().add("Strict-Transport-Security", value);
   }
   return response;
 }
 @Override
 public ContainerRequest filter(ContainerRequest request) {
   String callback = null;
   try {
     callback = httpServletRequest.getParameter("callback");
   } catch (IllegalStateException e) {
   }
   if (callback == null) {
     try {
       callback = request.getQueryParameters().getFirst("callback");
     } catch (IllegalStateException e) {
     }
   }
   if (isNotBlank(callback)) {
     request.getRequestHeaders().putSingle("Accept", "application/javascript");
   }
   return request;
 }
 private boolean isMissionControlAccesPoint(ContainerRequest request) {
   String baseUrl = request.getBaseUri().toString();
   baseUrl = PathUtils.trimLeadingSlashes(baseUrl);
   baseUrl = PathUtils.trimTrailingSlashes(baseUrl);
   if (baseUrl.endsWith("/mc")) {
     return true;
   }
   return false;
 }
 protected void addLink(String rel, Pagination p, ContainerRequest req, ContainerResponse res) {
   URI uri =
       req.getRequestUriBuilder()
           .replaceQueryParam(RESTConstants.LIMIT, p.getLimit())
           .replaceQueryParam(RESTConstants.PAGE, p.getPage())
           .build();
   MediaType type = res.getMediaType();
   LinkHeader header = LinkHeader.uri(uri).type(type).rel(rel).build();
   res.getHttpHeaders().add(LINK_HEADER, header.toString());
 }
  public ClientResponse handle(ClientRequest clientRequest) {
    byte[] requestEntity = writeRequestEntity(clientRequest);

    InBoundHeaders rh = getInBoundHeaders(clientRequest.getMetadata());

    final ContainerRequest cRequest =
        new ContainerRequest(
            w,
            clientRequest.getMethod(),
            baseUri,
            clientRequest.getURI(),
            rh,
            new ByteArrayInputStream(requestEntity));

    // TODO this is a hack
    List<String> cookies = cRequest.getRequestHeaders().get("Cookie");
    if (cookies != null) {
      for (String cookie : cookies) {
        if (cookie != null) cRequest.getCookies().putAll(HttpHeaderReader.readCookies(cookie));
      }
    }

    final TstContainerResponseWriter writer = new TstContainerResponseWriter();
    final ContainerResponse cResponse = new ContainerResponse(w, cRequest, writer);

    try {
      w.handleRequest(cRequest, cResponse);
    } catch (IOException e) {
      throw new ContainerException(e);
    }

    byte[] responseEntity = writer.baos.toByteArray();
    ClientResponse clientResponse =
        new ClientResponse(
            cResponse.getStatus(),
            getInBoundHeaders(cResponse.getHttpHeaders()),
            new ByteArrayInputStream(responseEntity),
            getMessageBodyWorkers());

    clientResponse.getProperties().put("request.entity", requestEntity);
    clientResponse.getProperties().put("response.entity", responseEntity);
    return clientResponse;
  }
示例#12
0
  // TODO used to see the requests content...
  @SuppressWarnings("unused")
  private ContainerRequest read(ContainerRequest request) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream in = request.getEntityInputStream();
    final StringBuilder b = new StringBuilder();
    try {
      if (in.available() > 0) {
        ReaderWriter.writeTo(in, out);

        byte[] requestEntity = out.toByteArray();
        printEntity(b, requestEntity);

        request.setEntityInputStream(new ByteArrayInputStream(requestEntity));
      }
      return request;
    } catch (IOException ex) {
      throw new ContainerException(ex);
    }
  }
 public boolean isFirstCallToSetupMC(ContainerRequest request) {
   MissionControlProperties missionControlProperties =
       ContextHelper.get().beanForType(MissionControlProperties.class);
   String token = missionControlProperties.getToken();
   String url = missionControlProperties.getUrl();
   if ((isBlank(url) || isBlank(token)) && request.getPath().endsWith("setupmc")) {
     return true;
   }
   return false;
 }
示例#14
0
  @Override
  public ContainerRequest filter(ContainerRequest request) {
    String path = request.getPath();
    log.info("Filtering request path: " + path);

    // IMPORTANT!!! First, Acknowledge any pre-flight test from browsers for
    // this case before validating the headers (CORS stuff)
    if (request.getMethod().equals("OPTIONS")) {
      log.info("en Options?");
      ResponseBuilder builder = null;
      String response = "OK";
      builder = Response.status(Response.Status.OK).entity(response);
      throw new WebApplicationException(builder.build());
    }

    // Then check is the service key exists and is valid.
    Authenticator demoAuthenticator = Authenticator.getInstance();
    String serviceKey = request.getHeaderValue(HttpHeaderNames.SERVICE_KEY);

    if (!demoAuthenticator.isServiceKeyValid(serviceKey)) {
      ResponseBuilder builder = null;
      String response = "Invalid Service Key";
      builder = Response.status(Response.Status.UNAUTHORIZED).entity(response);
      throw new WebApplicationException(builder.build());
    }

    // For any pther methods besides login, the authToken must be verified
    if (!path.startsWith("auth/login")) {
      String authToken = request.getHeaderValue(HttpHeaderNames.AUTH_TOKEN);

      // if it isn't valid, just kick them out.
      if (!demoAuthenticator.isAuthTokenValid(serviceKey, authToken)) {
        ResponseBuilder builder = null;
        String response = "Authentication is need";
        builder = Response.status(Response.Status.UNAUTHORIZED).entity(response);
        throw new WebApplicationException(builder.build());
      }
    }
    // read(request);

    return request;
  }
示例#15
0
  @Override
  public ContainerResponse filter(ContainerRequest req, ContainerResponse contResp) {

    LOGGER.info("Enter CORS filter");
    LOGGER.info("Request= { path:" + req.getPath() + ", method:" + req.getMethod() + " }");

    ResponseBuilder resp = Response.fromResponse(contResp.getResponse());
    resp.header("Access-Control-Allow-Origin", "*");
    resp.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");

    String reqHead = req.getHeaderValue("Access-Control-Request-Headers");

    if (null != reqHead && !reqHead.equals(null)) {
      resp.header("Access-Control-Allow-Headers", reqHead);
    }

    contResp.setResponse(resp.build());

    LOGGER.info("Exit CORS filter");

    return contResp;
  }
  @Override
  public ContainerRequest filter(ContainerRequest request) {

    final String accessToken = request.getHeaderValue("Authorization");

    Session session = null;
    TokenWrapper response = null;

    if (accessToken != null && accessToken.length() > 0) {
      try {
        PhiAuthClient.setHostname("http://evergreenalumniclub.com:7080/PhiAuth/rest");
        response = PhiAuthClient.validateToken(accessToken);
      } catch (URISyntaxException e) {
        throw new UnableToValidateException(
            String.valueOf(Math.random()),
            "Could not validate token due to URI exception." + e.getMessage());
      } catch (HttpException e) {
        throw new UnableToValidateException(
            String.valueOf(Math.random()),
            "Could not validate token due to http exception." + e.getMessage());
      } catch (IOException e) {
        throw new UnableToValidateException(
            String.valueOf(Math.random()), "Could not validate token due to IO exception.");
      } catch (DependentServiceException e) {
        throw e;
      } catch (UnableToValidateException e) {
        throw new WebApplicationException();
      }
    } else {
      throw new InvalidTokenException(String.valueOf(Math.random()), "No token provided");
    }

    // Set security context
    request.setSecurityContext(new PhiAuthSecurityContext(session, response));
    return request;
  }
  public static CacheRequestContext build(
      ContainerRequest request, Set<String> vary, boolean includeBody) {
    try {
      MessageDigest digest = MessageDigest.getInstance("SHA-1");

      for (String header : vary) {
        List<String> headerValues = request.getRequestHeader(header);

        if (headerValues != null && headerValues.size() > 0) {
          digest.update(header.getBytes(Charsets.UTF_8));
          digest.update((byte) 0xFD);

          for (String value : headerValues) {
            digest.update(value.getBytes(Charsets.UTF_8));
            digest.update((byte) 0xFE);
          }

          digest.update((byte) 0xFF);
        }
      }

      if (includeBody) {
        byte[] requestBody = request.getEntity(byte[].class);

        if (requestBody == null) {
          requestBody = new byte[0];
        }

        if (requestBody.length > 0) {
          digest.update("Body".getBytes(Charsets.UTF_8));
          digest.update((byte) 0xFD);

          digest.update(requestBody);
          digest.update((byte) 0xFF);
        }

        request.setEntityInputStream(new ByteArrayInputStream(requestBody));
      }

      String hash = new String(Base64.encode(digest.digest()), Charsets.US_ASCII);
      return new CacheRequestContext(
          request.getMethod(), request.getRequestUri(), request.getRequestHeaders(), hash);
    } catch (NoSuchAlgorithmException ex) {
      // This error should not occur since SHA-1 must be included with every java distribution
      throw Throwables.propagate(ex);
    }
  }
示例#18
0
  public static Variant selectVariant(ContainerRequest r, List<Variant> variants) {
    LinkedList<VariantHolder> vhs = getVariantHolderList(variants);

    Set<String> vary = new HashSet<String>();
    vhs = selectVariants(vhs, HttpHelper.getAccept(r), MEDIA_TYPE_DC, vary);
    vhs = selectVariants(vhs, HttpHelper.getAcceptLanguage(r), LANGUAGE_TAG_DC, vary);
    vhs = selectVariants(vhs, HttpHelper.getAcceptCharset(r), CHARSET_DC, vary);
    vhs = selectVariants(vhs, HttpHelper.getAcceptEncoding(r), ENCODING_DC, vary);

    if (vhs.isEmpty()) {
      return null;
    } else {
      StringBuilder varyHeader = new StringBuilder();
      for (String v : vary) {
        if (varyHeader.length() > 0) {
          varyHeader.append(',');
        }
        varyHeader.append(v);
      }
      r.getProperties().put(ContainerRequest.VARY_HEADER, varyHeader.toString());
      return vhs.iterator().next().v;
    }
  }
 private static ContainerRequest request(String... userAgent) {
   ContainerRequest request = mock(ContainerRequest.class);
   List<String> headers = Arrays.asList(userAgent);
   stub(request.getRequestHeader("User-Agent")).toReturn(headers);
   return request;
 }
 @Test
 public void shouldSwallowAnyExceptionsThrownByTheRequest() {
   ContainerRequest request = mock(ContainerRequest.class);
   stub(request.getRequestHeader(anyString())).toThrow(new RuntimeException());
   filter.filter(request);
 }
  @Override
  public ContainerRequest filter(ContainerRequest request) {
    // validate session still active
    AuthUtils.validateSession(this.request, uriInfo, response);
    boolean authenticated = authorizationService.isAuthenticated();
    boolean anonAccessEnabled = authorizationService.isAnonAccessEnabled();
    if (!authenticated) {
      if (anonAccessEnabled || uriInfo.getPath().indexOf("auth") != -1) {
        // If anon access is allowed and we didn't bother authenticating try to perform the action
        // as a user
        request.setSecurityContext(
            new RoleAuthenticator(UserInfo.ANONYMOUS, AuthorizationService.ROLE_USER));
      } else {
        throw new AuthorizationRestException();
      }
    } else {
      // Block all the REST calls that pass trough 'mc' entry point and are not authenticated by the
      // MS token authentication,
      // except the FIRST and only the FIRST call to the setupMC that can be authenticated by the
      // basic authentication,
      if (isMissionControlAccesPoint(request)) {
        boolean firstCallToSetupMC = isFirstCallToSetupMC(request);
        boolean tokenAuthentication = isTokenAuthentication(request);
        if (!firstCallToSetupMC && !tokenAuthentication) {
          // Block all the REST calls that pass trough 'mc' entry point and are not authenticated by
          // the MS token authentication,
          throw new AuthorizationRestException(
              "The access trough the 'mc' entry point is allowed only with token authentication");
        } else if ((firstCallToSetupMC && tokenAuthentication)) {
          // Block the setupMC REST calls that pass trough 'mc' entry point and are authenticated by
          // basic authentication except the first time.
          throw new AuthorizationRestException(
              "To initialize mission control chanel for the first time use user name and password ");
        } else {
          String username = authorizationService.currentUsername();
          request.setSecurityContext(
              new RoleAuthenticator(username, AuthorizationService.ROLE_ADMIN));
          return request;
        }
      }

      // Set the authenticated user and role
      String username = authorizationService.currentUsername();
      boolean admin = authorizationService.isAdmin();

      boolean ha =
          SecurityContextHolder.getContext().getAuthentication()
              instanceof HaSystemAuthenticationToken;
      if (ha) {
        request.setSecurityContext(new RoleAuthenticator(username, HaRestConstants.ROLE_HA));
        return request;
      }

      if (admin) {
        request.setSecurityContext(
            new RoleAuthenticator(username, AuthorizationService.ROLE_ADMIN));
      } else {
        request.setSecurityContext(new RoleAuthenticator(username, AuthorizationService.ROLE_USER));
      }
    }
    return request;
  }
 private boolean isTokenAuthentication(ContainerRequest request) {
   String missionControlToken = request.getHeaderValue(HEADER_NAME);
   return !isBlank(missionControlToken);
 }