javax.ws.rs.container.ContainerRequestContext Java Examples

The following examples show how to use javax.ws.rs.container.ContainerRequestContext. 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: CrossOriginResourceSharingFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {
    Message m = JAXRSUtils.getCurrentMessage();

    String httpMethod = (String)m.get(Message.HTTP_REQUEST_METHOD);
    if (HttpMethod.OPTIONS.equals(httpMethod)) {
        Response r = preflightRequest(m);
        if (r != null) {
            context.abortWith(r);
        }
    } else if (findResourceMethod) {
        Method method = getResourceMethod(m, httpMethod);
        simpleRequest(m, method);
    } else {
        m.getInterceptorChain().add(new CorsInInterceptor());
    }

}
 
Example #2
Source File: LoggingFilter.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
        throws IOException {
    final long id = aid.incrementAndGet();
    final StringBuilder b = new StringBuilder();

    printResponseLine(b, "Server responded with a response", id, responseContext.getStatus());
    printPrefixedHeaders(b, id, RESPONSE_PREFIX, responseContext.getStringHeaders());

    if (printEntity && responseContext.hasEntity()) {
        final OutputStream stream = new LoggingStream(b, responseContext.getEntityStream());
        responseContext.setEntityStream(stream);
        requestContext.setProperty(ENTITY_LOGGER_PROPERTY, stream);
        // not calling log(b) here - it will be called by the interceptor
    } else {
        log(b);
    }
}
 
Example #3
Source File: OntologyRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns an array of the imports closure in the requested format from the ontology
 * with the requested ID.
 *
 * @param context     the context of the request.
 * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:".
 * @param rdfFormat   the desired RDF return format. NOTE: Optional param - defaults to "jsonld".
 * @param branchIdStr the String representing the Branch Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the
 *                    master Branch.
 * @param commitIdStr the String representing the Commit Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the head
 *                    Commit. The provided commitId must be on the Branch identified by the provided branchId;
 *                    otherwise, nothing will be returned.
 * @return array of imported ontologies from the ontology with the requested ID in the requested format
 */
@GET
@Path("{recordId}/imported-ontologies")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Retrieves the JSON-LD of all imported ontologies.")
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response getImportsClosure(@Context ContainerRequestContext context,
                                  @PathParam("recordId") String recordIdStr,
                                  @DefaultValue("jsonld") @QueryParam("rdfFormat") String rdfFormat,
                                  @QueryParam("branchId") String branchIdStr,
                                  @QueryParam("commitId") String commitIdStr) {
    try {
        Set<Ontology> importedOntologies = getImportedOntologies(context, recordIdStr, branchIdStr, commitIdStr);
        ArrayNode arrayNode = mapper.createArrayNode();
        importedOntologies.stream()
                .map(ontology -> getOntologyAsJsonObject(ontology, rdfFormat))
                .forEach(arrayNode::add);
        return arrayNode.size() == 0 ? Response.noContent().build() : Response.ok(arrayNode.toString()).build();
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example #4
Source File: CrnkFilterTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void checkWebPathPrefixNullFilter() throws IOException {
	CrnkFeature feature = Mockito.mock(CrnkFeature.class);
	Mockito.when(feature.getWebPathPrefix()).thenReturn(null);
	Mockito.when(feature.getBoot()).thenThrow(new WebApplicationException("test"));

	CrnkFilter filter = new CrnkFilter(feature);
	UriInfo uriInfo = Mockito.mock(UriInfo.class);
	Mockito.when(uriInfo.getPath()).thenReturn("/tasks");
	Mockito.when(uriInfo.getQueryParameters()).thenReturn(Mockito.mock(MultivaluedMap.class));

	ContainerRequestContext requestContext = Mockito.mock(ContainerRequestContext.class);
	Mockito.when(requestContext.getUriInfo()).thenReturn(uriInfo);
	try {
		filter.filter(requestContext);
		Assert.fail();
	} catch (WebApplicationException e) {
		Assert.assertEquals("test", e.getMessage());
	}
}
 
Example #5
Source File: EndpointMetricsFilter.java    From syndesis with Apache License 2.0 6 votes vote down vote up
/**
 * Called after the resource method.
 */
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {
    Sample sample = (Sample) requestContext.getProperty(TIMING_SAMPLE);
    if (sample != null) {
        Timer timer = Timer
            .builder("http.server.requests")
            // no way to access the exception
            .tag("exception", "")
            .tag("outcome", computeOutcome(responseContext))
            .tag("method", getMethod(requestContext))
            .tag("status", getStatus(responseContext))
            .tag("uri", getUri())
            .publishPercentileHistogram()
            .maximumExpectedValue(Duration.ofSeconds(10))
            .register(registry);
        sample.stop(timer);
    }
}
 
Example #6
Source File: TenantFilter.java    From hawkular-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    UriInfo uriInfo = requestContext.getUriInfo();
    String path = uriInfo.getPath();

    if (path.startsWith("/tenants") || path.startsWith(StatusHandler.PATH) || path.equals(BaseHandler.PATH)) {
        // Some handlers do not check the tenant header
        return;
    }

    String tenant = requestContext.getHeaders().getFirst(TENANT_HEADER_NAME);
    if (tenant != null && !tenant.trim().isEmpty()) {
        // We're good already
        return;
    }
    // Fail on missing tenant info
    Response response = Response.status(Status.BAD_REQUEST)
                                .type(APPLICATION_JSON_TYPE)
                                .entity(new ApiError(MISSING_TENANT_MSG))
                                .build();
    requestContext.abortWith(response);
}
 
Example #7
Source File: ClientCredentialsSecurityFilter.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Override
public void filter( ContainerRequestContext request ) {
    if (logger.isTraceEnabled()) {
        logger.trace("Filtering: {}", request.getUriInfo().getBaseUri());
    }

    if( bypassSecurityCheck(request) ){
        return;
    }

    String clientId = httpServletRequest.getParameter( "client_id" );
    String clientSecret = httpServletRequest.getParameter( "client_secret" );

    if ( isNotBlank( clientId ) && isNotBlank( clientSecret ) ) {
        try {
            PrincipalCredentialsToken token =
                    management.getPrincipalCredentialsTokenForClientCredentials( clientId, clientSecret );
            Subject subject = SubjectUtils.getSubject();
            subject.login( token );
        }
        catch ( Exception e ) {
            throw mappableSecurityException( OAUTH2_INVALID_CLIENT );
        }
    }
}
 
Example #8
Source File: ResponseWrapperHandler.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
@Override
public void processResponse(ContainerRequestContext requestContext, ContainerResponseContext responseContext,
		ResourceInfo resourceInfo) {
	MediaType mediaType = responseContext.getMediaType();
	if (mediaType != null && MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) {
		Object responseData = responseContext.getEntity();
		WrapperResponseEntity jsonResponse;

		if (responseData instanceof WrapperResponseEntity) {
			jsonResponse = (WrapperResponseEntity) responseData;
		} else {
			jsonResponse = new WrapperResponseEntity(ResponseCode.OK);
			jsonResponse.setData(responseData);
		}
		responseContext.setStatus(ResponseCode.OK.getCode());

		responseContext.setEntity(jsonResponse);

	}
}
 
Example #9
Source File: PerRequestTestFilter.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext)
    throws IOException {

    Class<?> matchedResource = (Class<?>)requestContext.
        getUriInfo().
        getMatchedResources().
        get(0);

    Object resource = _resourceContext.getResource(matchedResource);

    if (resource instanceof PerRequestTestResource) {
        PerRequestTestResource perRequestTestResource =
            (PerRequestTestResource) resource;

        perRequestTestResource.setState(perRequestTestResource.getState() + "-changed");
    }
}
 
Example #10
Source File: JwtAuthFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testJwtAuthFilter() {
    final ContainerRequestContext mockContext = mock(ContainerRequestContext.class);
    assertNotNull(filter);
    assertNotNull(producer);

    final String iss = "https://example.com/idp/";
    final String sub = "acoburn";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(sub);
    claims.setIssuer(iss);

    producer.setJsonWebToken(new DefaultJWTCallerPrincipal(claims));
    assertDoesNotThrow(() -> filter.filter(mockContext));
    verify(mockContext).setSecurityContext(securityArgument.capture());
    assertEquals(iss + sub, securityArgument.getValue().getUserPrincipal().getName());
}
 
Example #11
Source File: CookieParamProvider.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
@Override
public Object provideValue(Parameter parameter, ContainerRequestContext requestContext, ObjectMapper objectMapper) {
    Object returnValue;
    String cookieName = parameter.getAnnotation(CookieParam.class).value();
    Cookie cookie = requestContext.getCookies().get(cookieName);
    if (cookie == null) {
        return null;
    } else {
        if (Cookie.class.isAssignableFrom(parameter.getType())) {
            returnValue = cookie;
        } else if (String.class.isAssignableFrom(parameter.getType())) {
            returnValue = cookie.getValue();
        } else {
            try {
                returnValue = objectMapper.readValue(cookie.getValue(), parameter.getType());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    return returnValue;
}
 
Example #12
Source File: PageResourceNotAuthenticatedTest.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
    requestContext.setSecurityContext(new SecurityContext() {
        @Override
        public Principal getUserPrincipal() {
            return null;
        }
        @Override
        public boolean isUserInRole(String string) {
            return false;
        }
        @Override
        public boolean isSecure() { return false; }
        
        @Override
        public String getAuthenticationScheme() { return "BASIC"; }
    });
}
 
Example #13
Source File: StructuredEventFilter.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
    if (BooleanUtils.isTrue((Boolean) requestContext.getProperty(LOGGING_ENABLED_PROPERTY))) {
        RestResponseDetails restResponse = createResponseDetails(responseContext);
        if (responseContext.hasEntity()) {
            OutputStream stream = new LoggingStream(responseContext.getEntityStream());
            responseContext.setEntityStream(stream);
            requestContext.setProperty(LOGGINGSTREAM_PROPERTY, stream);
            requestContext.setProperty(RESPONSE_DETAILS, restResponse);
        } else {
            Long requestTime = (Long) requestContext.getProperty(REQUEST_TIME);
            RestRequestDetails restRequest = (RestRequestDetails) requestContext.getProperty(REQUEST_DETAILS);
            Map<String, String> restParams = (Map<String, String>) requestContext.getProperty(REST_PARAMS);
            sendStructuredEvent(restRequest, restResponse, restParams, requestTime, "");
        }
    }
}
 
Example #14
Source File: CORSFilter.java    From helix with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext request) throws IOException {
  // handle preflight
  if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
    Response.ResponseBuilder builder = Response.ok();

    String requestMethods = request.getHeaderString("Access-Control-Request-Method");
    if (requestMethods != null) {
      builder.header("Access-Control-Allow-Methods", requestMethods);
    }

    String allowHeaders = request.getHeaderString("Access-Control-Request-Headers");
    if (allowHeaders != null) {
      builder.header("Access-Control-Allow-Headers", allowHeaders);
    }

    request.abortWith(builder.build());
  }
}
 
Example #15
Source File: RpcContextFilter.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public void filter(ContainerRequestContext requestContext) throws IOException {
    HttpServletRequest request = ResteasyProviderFactory.getContextData(HttpServletRequest.class);
    RpcContext.getContext().setRequest(request);

    // this only works for servlet containers
    if (request != null && RpcContext.getContext().getRemoteAddress() == null) {
        RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort());
    }

    RpcContext.getContext().setResponse(ResteasyProviderFactory.getContextData(HttpServletResponse.class));

    String headers = requestContext.getHeaderString(DUBBO_ATTACHMENT_HEADER);
    if (headers != null) {
        for (String header : headers.split(",")) {
            int index = header.indexOf("=");
            if (index > 0) {
                String key = header.substring(0, index);
                String value = header.substring(index + 1);
                if (!StringUtils.isEmpty(key)) {
                    RpcContext.getContext().setAttachment(key.trim(), value.trim());
                }
            }
        }
    }
}
 
Example #16
Source File: ClientCodeRequestFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
private Response createCodeResponse(ContainerRequestContext rc, UriInfo ui) {
    MultivaluedMap<String, String> codeRequestState = toCodeRequestState(rc, ui);
    MultivaluedMap<String, String> redirectState = createRedirectState(rc, ui, codeRequestState);
    String theState = redirectState != null ? redirectState.getFirst(OAuthConstants.STATE) : null;
    String redirectScope = redirectState != null ? redirectState.getFirst(OAuthConstants.SCOPE) : null;
    String theScope = redirectScope != null ? redirectScope : scopes;
    UriBuilder ub = OAuthClientUtils.getAuthorizationURIBuilder(authorizationServiceUri,
                                         consumer.getClientId(),
                                         getAbsoluteRedirectUri(ui).toString(),
                                         theState,
                                         theScope);
    setFormPostResponseMode(ub, redirectState);
    setCodeVerifier(ub, redirectState);
    setAdditionalCodeRequestParams(ub, redirectState, codeRequestState);
    URI uri = ub.build();
    return Response.seeOther(uri).build();
}
 
Example #17
Source File: OntologyRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Delete class with requested class ID from ontology identified by the provided IDs from the server.
 *
 * @param context     the context of the request.
 * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:".
 * @param classIdStr  the String representing the class Resource id. NOTE: Assumes id represents
 *                    an IRI unless String begins with "_:".
 * @param branchIdStr the String representing the Branch Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the
 *                    master Branch.
 * @param commitIdStr the String representing the Commit Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the head
 *                    Commit. The provided commitId must be on the Branch identified by the provided branchId;
 *                    otherwise, nothing will be returned.
 * @return a Response indicating whether it was successfully deleted.
 */
@DELETE
@Path("{recordId}/classes/{classId}")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Deletes the identified class from the identified ontology.")
@ActionId(Modify.TYPE)
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response deleteClassFromOntology(@Context ContainerRequestContext context,
                                        @PathParam("recordId") String recordIdStr,
                                        @PathParam("classId") String classIdStr,
                                        @QueryParam("branchId") String branchIdStr,
                                        @QueryParam("commitId") String commitIdStr) {
    try {
        Ontology ontology = getOntology(context, recordIdStr, branchIdStr, commitIdStr, true).orElseThrow(() ->
                ErrorUtils.sendError("The ontology could not be found.", Response.Status.BAD_REQUEST));
        return deletionsToInProgressCommit(context, ontology, classIdStr, recordIdStr);
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example #18
Source File: TestAuthenticationFilter.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext) {
    requestContext.setSecurityContext(new SecurityContext() {
        @Override
        public Principal getUserPrincipal() {
            return () -> principal;
        }

        @Override
        public boolean isSecure() {
            return false;
        }

        @Override
        public boolean isUserInRole(final String role) {
            return userRole.equals(role);
        }

        @Override
        public String getAuthenticationScheme() {
            return "BASIC";
        }
    });
}
 
Example #19
Source File: SetupAuthorizationFilter.java    From g-suite-identity-sync with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    OidcSecurityContext secCtx = (OidcSecurityContext) requestContext.getSecurityContext();
    OidcClientTokenContext tokenCtx = secCtx.getOidcContext();
    IdToken idToken = tokenCtx.getIdToken();
    String email = idToken.getEmail();
    boolean configured = false;
    try {
        configured = googleConfig.getServiceAccountEmail() != null && googleConfig.readServiceAccountKey() != null;
    } catch (NoPrivateKeyException e) {
    }
    if (configured) {
        log.error("Unauthorized access from {}. Application is already configured!", email);
        ServerError err = new ServerError("E002", "Unauthorized access to Configuration API");
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(err).type(MediaType.APPLICATION_JSON).build());
    }
}
 
Example #20
Source File: MetricsFilter.java    From keycloak-metrics-spi with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext req, ContainerResponseContext res) {
    int status = res.getStatus();

    // We are only interested in recording the response status if it was an error
    // (either a 4xx or 5xx). No point in counting  the successful responses
    if (status >= 400) {
        PrometheusExporter.instance().recordResponseError(status, req.getMethod());
    }

    // Record request duration if timestamp property is present
    // and only if it is relevant (skip pictures)
    if (req.getProperty(METRICS_REQUEST_TIMESTAMP) != null &&
        contentTypeIsRelevant(res)) {
        long time = (long) req.getProperty(METRICS_REQUEST_TIMESTAMP);
        long dur = System.currentTimeMillis() - time;
        LOG.trace("Duration is calculated as " + dur + " ms.");
        PrometheusExporter.instance().recordRequestDuration(dur, req.getMethod());
    }
}
 
Example #21
Source File: CORSFilter.java    From aerogear-unifiedpush-server with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext,
                   ContainerResponseContext responseContext) throws IOException {
    responseContext.getHeaders().add(
            "Access-Control-Allow-Origin", "*");
    responseContext.getHeaders().add(
            "Access-Control-Allow-Credentials", "true");
    responseContext.getHeaders().add(
            "Access-Control-Allow-Headers",
            "origin, content-type, accept, authorization");
    responseContext.getHeaders().add(
            "Access-Control-Allow-Methods",
            "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    responseContext.getHeaders().add(
            "Access-Control-Expose-Headers", "*");
}
 
Example #22
Source File: OntologyRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Returns annotation property IRIs in the imports closure for the ontology identified by the provided IDs.
 *
 * @param context     the context of the request.
 * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:".
 * @param branchIdStr the String representing the Branch Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the
 *                    master Branch.
 * @param commitIdStr the String representing the Commit Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the head
 *                    Commit. The provided commitId must be on the Branch identified by the provided branchId;
 *                    otherwise, nothing will be returned.
 * @return annotation properties in the ontology identified by the provided IDs.
 */
@GET
@Path("{recordId}/imported-annotations")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Gets the annotations from the imported ontologies of the identified ontology.")
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response getAnnotationsInImportedOntologies(@Context ContainerRequestContext context,
                                                   @PathParam("recordId") String recordIdStr,
                                                   @QueryParam("branchId") String branchIdStr,
                                                   @QueryParam("commitId") String commitIdStr) {
    try {
        return doWithImportedOntologies(context, recordIdStr, branchIdStr, commitIdStr,
                this::getAnnotationIRIObject);
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
Example #23
Source File: RestSecurityInterceptor.java    From opensoc-streaming with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	
	// get our token...		
	Map<String, Cookie> cookies = requestContext.getCookies();
	
	Cookie authTokenCookie = cookies.get( "authToken" );
	if( authTokenCookie == null )
	{
		requestContext.abortWith(ACCESS_DENIED );
		return;			
	}
	
	String authToken = authTokenCookie.getValue();
	try {
		
		if( ! AuthToken.validateToken(configProps, authToken) )
		{
			requestContext.abortWith(ACCESS_DENIED );
			return;	
		}
	} 
	catch (Exception e) {

		e.printStackTrace();
		requestContext.abortWith(ACCESS_DENIED );
		return;
	}

	// if the token is good, just return...
	
}
 
Example #24
Source File: MCRIIIFBaseURLFilter.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override public void filter(ContainerRequestContext requestContext) throws IOException {
    // set BASE_URL_ATTRIBUTE to MCRSession
    if (httpRequest.getAttribute(BASE_URL_ATTRIBUTE) != null) {
        final MCRSession currentSession = MCRSessionMgr.getCurrentSession();
        if (currentSession != null) {
            currentSession.put(BASE_URL_ATTRIBUTE, httpRequest.getAttribute(BASE_URL_ATTRIBUTE));
        }
    }
}
 
Example #25
Source File: CorsFilterTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Test
public void preflightRequestFilter_BlankMethodGiven_CorsFails() throws IOException {
	CorsFilter filter = new CorsFilter.Builder()
			.allowMethod(HttpMethod.GET)
			.build();
	ContainerRequestContext request = createPreflightRequestMock(DEFAULT_HOST, DEFAULT_ORIGIN, " ");
	assertThrows(ForbiddenException.class, () -> filter.filter(request));
}
 
Example #26
Source File: CrossOriginResourceSharingFilter.java    From trellis with Apache License 2.0 5 votes vote down vote up
private Map<String, String> handleSimpleRequest(final ContainerRequestContext req) {
    final Map<String, String> headers = new HashMap<>();
    final String origin = req.getHeaderString("Origin");

    // 6.1.1 Terminate if an Origin header is not present
    if (origin == null) {
        LOGGER.debug("CORS: No Origin header");
        return emptyMap();
    }

    // 6.1.2 Check for a case-sensitive match of the origin header string
    if (!originMatches(origin)) {
        LOGGER.debug("CORS: No Origin header match");
        return emptyMap();
    }

    // 6.1.3 Add the origin and credentials values
    headers.put("Access-Control-Allow-Origin", origin);
    if (credentials) {
        headers.put("Access-Control-Allow-Credentials", "true");
    }

    if (!exposedHeaders.isEmpty()) {
        headers.put("Access-Control-Expose-Headers", join(",", exposedHeaders));
    }

    return headers;
}
 
Example #27
Source File: CorsResponseFilter.java    From cors with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
    final MultivaluedMap<String, Object> headers = responseContext.getHeaders();
    headers.add("Access-Control-Allow-Origin", "*");
    headers.add("Access-Control-Allow-Headers", getRequestedAllowedHeaders(requestContext));
    headers.add("Access-Control-Expose-Headers", getRequestedExposedHeaders(requestContext));
    headers.add("Access-Control-Allow-Credentials", "true");
    headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS);
    headers.add("Access-Control-Max-Age", MAX_AGE);
    headers.add("x-responded-by", "cors-response-filter");
}
 
Example #28
Source File: CorsFilterTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Test
public void requestFilter_CustomAlwaysSameOriginPolicyGiven_SkipsFiltering() throws IOException, URISyntaxException {
	CorsFilter filter = new CorsFilter.Builder()
			.sameOriginPolicy((containerRequestContext, origin) -> true)
			.build();
	ContainerRequestContext request = createPreflightRequestMock(DEFAULT_HOST, DEFAULT_ORIGIN, HttpMethod.GET);
	filter.filter(request);
	verify(request, never()).abortWith(any());
}
 
Example #29
Source File: CorsResponseFilter.java    From genesis with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Allows the request to go through as an exception
 *
 * @param requestContext the request context
 * @param responseContext the response context
 * @param origin the request's origin
 */
private void allowExceptionCors(ContainerRequestContext requestContext, ContainerResponseContext responseContext, String origin) {
    //Gets the method header
    String methodHeader = requestContext.getHeaderString("Access-Control-Request-Method");
    //Gets the request headers
    String requestHeaders = requestContext.getHeaderString("Access-Control-Request-Headers");

    //Get the headers from the response context
    MultivaluedMap<String, Object> headers = responseContext.getHeaders();
    //Set multiple fields in the header
    headers.putSingle("Access-Control-Allow-Origin", origin);
    headers.putSingle("Access-Control-Allow-Credentials", "true");
    headers.putSingle("Access-Control-Allow-Methods", methodHeader);
    headers.putSingle("Access-Control-Allow-Headers", "x-requested-with," + (requestHeaders == null ? "" : requestHeaders));
}
 
Example #30
Source File: CORSFilter.java    From liberty-bikes with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
    responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
    responseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
    responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
    responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    responseContext.getHeaders().add("Access-Control-Max-Age", "1209600");
}