Java Code Examples for javax.ws.rs.container.ContainerRequestContext#getHeaders()

The following examples show how to use javax.ws.rs.container.ContainerRequestContext#getHeaders() . 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: ReplaceES419LanguageFilter.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext request) {
  MultivaluedMap<String, String> headers = request.getHeaders();
  if (headers.containsKey(HttpHeaders.ACCEPT_LANGUAGE)) {
    List<String> acceptLanguageValues = headers.remove(HttpHeaders.ACCEPT_LANGUAGE);

    for (int i = 0; i < acceptLanguageValues.size(); i++) {
      final String acceptLanguageValue = acceptLanguageValues.get(i);

      // replace es-419 (invalid) with es_ES (valid, hopefully good enough.)
      if (acceptLanguageValue.contains(ES_419)) {
        acceptLanguageValues.set(i, acceptLanguageValue.replace(ES_419, ES_ES));
      }
    }

    headers.put(HttpHeaders.ACCEPT_LANGUAGE, acceptLanguageValues);
  }
}
 
Example 2
Source File: ContainerSecurityRequestFilter.java    From Cheddar with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
    final MultivaluedMap<String, String> headers = requestContext.getHeaders();
    final String userId = getValueForHeaderAndScheme(headers, HttpHeaders.AUTHORIZATION, CLICK_PLATFORM_SCHEME);
    final String teamId = getValueForHeaderAndScheme(headers, CLICK_PLATFORM_TEAM_ID_HEADER, CLICK_PLATFORM_SCHEME);
    final String agentUserId = getValueForHeaderAndScheme(headers, CLICK_PLATFORM_AGENT_AUTHORIZATION_HEADER,
            CLICK_PLATFORM_SCHEME);
    final String appId = getValueForHeader(headers, CLICK_PLATFORM_APP_ID_HEADER);
    SecurityContextHolder.set(new DefaultSecurityContext(userId, teamId, agentUserId, appId));
}
 
Example 3
Source File: JwsJsonContainerRequestFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) throws IOException {
    if (isMethodWithNoContent(context.getMethod())
        || isCheckEmptyStream() && !context.hasEntity()) {
        return;
    }
    final String content = IOUtils.readStringFromStream(context.getEntityStream());
    if (StringUtils.isEmpty(content)) {
        return;
    }
    JwsSignatureVerifier theSigVerifier = getInitializedSigVerifier();
    JwsJsonConsumer c = new JwsJsonConsumer(content);
    try {
        validate(c, theSigVerifier);
    } catch (JwsException ex) {
        context.abortWith(JAXRSUtils.toResponse(400));
        return;
    }

    byte[] bytes = c.getDecodedJwsPayloadBytes();
    context.setEntityStream(new ByteArrayInputStream(bytes));
    context.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));

    // the list is guaranteed to be non-empty
    JwsJsonSignatureEntry sigEntry = c.getSignatureEntries().get(0);
    String ct = JoseUtils.checkContentType(sigEntry.getUnionHeader().getContentType(), getDefaultMediaType());
    if (ct != null) {
        context.getHeaders().putSingle("Content-Type", ct);
    }
    if (super.isValidateHttpHeaders()) {
        super.validateHttpHeadersIfNeeded(context.getHeaders(), sigEntry.getProtectedHeader());
    }
}
 
Example 4
Source File: JwsContainerRequestFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) throws IOException {
    if (isMethodWithNoContent(context.getMethod())
        || isCheckEmptyStream() && !context.hasEntity()) {
        return;
    }
    final String content = IOUtils.readStringFromStream(context.getEntityStream());
    if (StringUtils.isEmpty(content)) {
        return;
    }
    JwsCompactConsumer p = new JwsCompactConsumer(content);
    JwsSignatureVerifier theSigVerifier = getInitializedSigVerifier(p.getJwsHeaders());
    if (!p.verifySignatureWith(theSigVerifier)) {
        context.abortWith(JAXRSUtils.toResponse(400));
        return;
    }
    JoseUtils.validateRequestContextProperty(p.getJwsHeaders());
    
    byte[] bytes = p.getDecodedJwsPayloadBytes();
    context.setEntityStream(new ByteArrayInputStream(bytes));
    context.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));

    String ct = JoseUtils.checkContentType(p.getJwsHeaders().getContentType(), getDefaultMediaType());
    if (ct != null) {
        context.getHeaders().putSingle("Content-Type", ct);
    }

    if (super.isValidateHttpHeaders()) {
        super.validateHttpHeadersIfNeeded(context.getHeaders(), p.getJwsHeaders());
    }
    
    Principal currentPrincipal = context.getSecurityContext().getUserPrincipal();
    if (currentPrincipal == null || currentPrincipal.getName() == null) {
        SecurityContext securityContext = configureSecurityContext(theSigVerifier);
        if (securityContext != null) {
            JAXRSUtils.getCurrentMessage().put(SecurityContext.class, securityContext);
        }
    }
}
 
Example 5
Source File: OpenTracingProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void filter(final ContainerRequestContext requestContext,
        final ContainerResponseContext responseContext) throws IOException {
    super.stopTraceSpan(requestContext.getHeaders(), responseContext.getHeaders(),
        responseContext.getStatus(), (TraceScopeHolder<TraceScope>)requestContext.getProperty(TRACE_SPAN));
}
 
Example 6
Source File: OpenTracingProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
    final TraceScopeHolder<TraceScope> holder = super.startTraceSpan(requestContext.getHeaders(),
        requestContext.getUriInfo().getRequestUri(), requestContext.getMethod());

    if (holder != null) {
        requestContext.setProperty(TRACE_SPAN, holder);
    }
}
 
Example 7
Source File: BraveProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void filter(final ContainerRequestContext requestContext,
        final ContainerResponseContext responseContext) throws IOException {
    super.stopTraceSpan(requestContext.getHeaders(), responseContext.getHeaders(),
        responseContext.getStatus(), (TraceScopeHolder<TraceScope>)requestContext.getProperty(TRACE_SPAN));
}
 
Example 8
Source File: BraveProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
    final TraceScopeHolder<TraceScope> holder = super.startTraceSpan(requestContext.getHeaders(),
        requestContext.getUriInfo().getRequestUri(), requestContext.getMethod());

    if (holder != null) {
        requestContext.setProperty(TRACE_SPAN, holder);
    }
}
 
Example 9
Source File: StreamingWriterInterceptor.java    From ameba with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
    if (isWritable(context)) {
        MultivaluedMap<String, Object> respHeaders = context.getHeaders();
        ContainerRequestContext requestContext = requestProvider.get();
        MultivaluedMap<String, String> reqHeaders = requestContext.getHeaders();
        if (reqHeaders.containsKey(MediaStreaming.RANGE)) {
            if (reqHeaders.containsKey(IF_RANGE)) {
                String ifRangeHeader = reqHeaders.getFirst(IF_RANGE);
                if (StringUtils.isBlank(ifRangeHeader)) {
                    return;
                }
                if (respHeaders.containsKey(HttpHeaders.ETAG)) {
                    if (MessageHelper.getHeaderString(respHeaders, HttpHeaders.ETAG)
                            .equals(ifRangeHeader)) {
                        applyStreaming(requestContext, context);
                        return;
                    }
                }
                if (respHeaders.containsKey(HttpHeaders.LAST_MODIFIED)) {
                    if (MessageHelper.getHeaderString(respHeaders, HttpHeaders.LAST_MODIFIED)
                            .equals(ifRangeHeader)) {
                        applyStreaming(requestContext, context);
                    }
                }
            } else {
                applyStreaming(requestContext, context);
            }
        }
    }
    context.proceed();
}
 
Example 10
Source File: ContainerFeatureSetRequestFilter.java    From Cheddar with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
    final MultivaluedMap<String, String> headersMap = requestContext.getHeaders();
    FeaturesContextHolder.clear();
    if (headersMap.containsKey(FEATURE_SET_ID_HEADER)) {
        for (final String featureSetId : headersMap.get(FEATURE_SET_ID_HEADER)) {
            if (!featureSetId.isEmpty()) {
                FeaturesContextHolder.set(new FeaturesContext(featureSetId));
            }
        }
    }
}
 
Example 11
Source File: RequestLoggingFilter.java    From pnc with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    MDCUtils.clear();
    requestContext.setProperty(REQUEST_EXECUTION_START, System.currentTimeMillis());

    String logRequestContext = requestContext.getHeaderString("log-request-context");
    if (logRequestContext == null) {
        logRequestContext = RandomUtils.randString(12);
    }
    MDCUtils.addRequestContext(logRequestContext);

    String logProcessContext = requestContext.getHeaderString("log-process-context");
    if (logProcessContext != null) {
        MDCUtils.addProcessContext(logProcessContext);
    }

    User user = null;
    try {
        user = userService.currentUser();
        if (user != null) {
            Integer userId = user.getId();
            if (userId != null) {
                MDCUtils.addUserId(Integer.toString(userId));
            }
        }
    } catch (Exception e) {
        // user not found, continue ...
    }

    UriInfo uriInfo = requestContext.getUriInfo();
    Request request = requestContext.getRequest();
    logger.info("Requested {} {}.", request.getMethod(), uriInfo.getRequestUri());

    if (logger.isTraceEnabled()) {
        MultivaluedMap<String, String> headers = requestContext.getHeaders();
        logger.trace("Headers: " + MapUtils.toString(headers));
        logger.trace("Entity: {}.", getEntityBody(requestContext));
        logger.trace("User principal name: {}", getUserPrincipalName(requestContext));
    }
}
 
Example 12
Source File: JweJsonContainerRequestFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) throws IOException {
    if (isMethodWithNoContent(context.getMethod())
        || isCheckEmptyStream() && !context.hasEntity()) {
        return;
    }
    final byte[] encryptedContent = IOUtils.readBytesFromStream(context.getEntityStream());
    if (encryptedContent.length == 0) {
        return;
    }
    try {
        JweDecryptionOutput out = decrypt(encryptedContent);
        byte[] bytes = out.getContent();
        context.setEntityStream(new ByteArrayInputStream(bytes));
        context.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));
        String ct = JoseUtils.checkContentType(out.getHeaders().getContentType(), getDefaultMediaType());
        if (ct != null) {
            context.getHeaders().putSingle("Content-Type", ct);
        }
        if (super.isValidateHttpHeaders()) {
            super.validateHttpHeadersIfNeeded(context.getHeaders(), out.getHeaders());
        }
    } catch (JweException ex) {
        context.abortWith(JAXRSUtils.toResponse(400));
        return;
    }
}
 
Example 13
Source File: AuthInterceptor.java    From enmasse with Apache License 2.0 5 votes vote down vote up
static Map<String, List<String>> findExtra(ApiHeaderConfig apiHeaderConfig, ContainerRequestContext requestContext) {
    Map<String, List<String>> extras = new HashMap<>();
    MultivaluedMap<String, String> headers = requestContext.getHeaders();
    if (headers != null) {
        for (String extraHeaderPrefix : apiHeaderConfig.getExtraHeadersPrefix()) {
            for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
                if (entry.getKey().startsWith(extraHeaderPrefix)) {
                    String key = entry.getKey().substring(extraHeaderPrefix.length()).toLowerCase();
                    extras.put(key, entry.getValue());
                }
            }
        }
    }
    return extras;
}
 
Example 14
Source File: MCRRemoveMsgBodyFilter.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    MultivaluedMap<String, String> headers = requestContext.getHeaders();
    if (headers.containsKey(IGNORE_MESSAGE_BODY_HEADER)) {
        LOGGER.info("Found {} header. Remove request message body.", IGNORE_MESSAGE_BODY_HEADER);
        headers.remove(IGNORE_MESSAGE_BODY_HEADER);
        headers.remove(HttpHeaders.CONTENT_LENGTH);
        headers.remove("Transfer-Encoding");
        requestContext.setEntityStream(null);
    }
}
 
Example 15
Source File: TestRequestFilter.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) {
	this.lastReceivedHeaders = requestContext.getHeaders();
}
 
Example 16
Source File: LoggingResourceFilter.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private void logResponse(ContainerRequestContext requestContext, ContainerResponseContext responseContext, Duration requestDuration, LogLevel level) {
    if (!isLogEnabled(LOG, level)) return;
    
    int status = responseContext.getStatus();
    String method = requestContext.getMethod();
    String path = requestContext.getUriInfo().getPath();
    requestContext.getSecurityContext();
    MultivaluedMap<String, String> queryParams = requestContext.getUriInfo().getQueryParameters();
    
    SecurityContext securityContext = requestContext.getSecurityContext();
    Principal userPrincipal = (securityContext != null) ? requestContext.getSecurityContext().getUserPrincipal() : null;
    String userName = (userPrincipal != null) ? userPrincipal.getName() : "<no-user>";
    String remoteAddr = servletRequest.getRemoteAddr();
    
    boolean includeHeaders = (responseContext.getStatus() / 100 == 5) || LOG.isTraceEnabled();

    StringBuilder message = new StringBuilder("Request completed: ")
            .append("status ")
            .append(status)
            .append(" in ")
            .append(requestDuration)
            .append(", ")
            .append(method)
            .append(" ")
            .append(path)
            .append(" from ")
            .append(userName)
            .append(" @ ")
            .append(remoteAddr);

    if (!queryParams.isEmpty()) {
        message.append(", queryParams: {");
        message.append(Joiner.on(", ").withKeyValueSeparator("=").join(queryParams));
        message.append("}");
    }
    if (requestContext.getLength() > 0) {
        // TODO `getLength` is based on the presence of `Content-Length` header, rather than the measured length.
        int len = requestContext.getLength();
        message.append(", mediaType=").append(requestContext.getMediaType())
                .append(" (length=").append(len).append(")");
    }
    if (includeHeaders) {
        MultivaluedMap<String, String> headers = requestContext.getHeaders();
        message.append(", headers={");
        if (!headers.isEmpty()) {
            boolean first = true;
            for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
                if (first) {
                    first = false;
                } else {
                    message.append(", ");
                }
                String headerName = entry.getKey();
                message.append(headerName).append(": ");
                if (CENSORED_HEADERS.contains(headerName)) {
                    message.append("******");
                } else {
                    message.append(entry.getValue());
                }
            }
        }
        message.append("}");
    }

    log(LOG, level, message.toString());
}
 
Example 17
Source File: SecurityFilter.java    From maven-framework-project with MIT License 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) {
	ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext
			.getProperty(RESOURCE_METHOD_INVOKER);
	Method method = methodInvoker.getMethod();
	// Access allowed for all
	if (!method.isAnnotationPresent(PermitAll.class)) {
		// Access denied for all
		if (method.isAnnotationPresent(DenyAll.class)) {
			requestContext.abortWith(ACCESS_FORBIDDEN);
			return;
		}

		// Get request headers
		final MultivaluedMap<String, String> headersMap = requestContext.getHeaders();

		// Fetch authorization header
		final List<String> authorizationList = headersMap.get(AUTHORIZATION_PROPERTY);

		// If no authorization information present; block access
		if (authorizationList == null || authorizationList.isEmpty()) {
			requestContext.abortWith(ACCESS_DENIED);
			return;
		}

		// Get encoded username and password
		final String encodedUserPassword = authorizationList.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", "");

		// Decode username and password
		String usernameAndPassword = new String(Base64.decodeBase64(encodedUserPassword));

		// Split username and password tokens
		final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
		final String userName = tokenizer.nextToken();
		final String password = tokenizer.nextToken();

		// Verify user access
		if (method.isAnnotationPresent(RolesAllowed.class)) {
			RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
			Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));

			// Is user valid?
			if (!isUserAllowed(userName, password, rolesSet)) {
				requestContext.abortWith(ACCESS_DENIED);
				return;
			}
		}
	}
}
 
Example 18
Source File: AuthenticationRequestFilter.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) {
    Method method = resourceInfo.getResourceMethod();
    //Access allowed for all
    if (!method.isAnnotationPresent(PermitAll.class)) {
        //Access denied for all
        if (method.isAnnotationPresent(DenyAll.class)) {
            requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity(AuthenticationRequestFilter.ERROR_ACCESS_FORBIDDEN).build());
            return;
        }

        //Get request headers
        final MultivaluedMap<String, String> headers = requestContext.getHeaders();

        //Fetch authorization header
        final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY);

        //If no authorization information present; block access
        if (authorization == null || authorization.isEmpty()) {

            requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(AuthenticationRequestFilter.ERROR_ACCESS_DENIED).build());
            return;
        }

        //Get encoded username and password
        final String encodedUserPassword = authorization.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", "");

        //Decode username and password
        String usernameAndPassword = new String(Base64.decode(encodedUserPassword.getBytes()));

        //Split username and password tokens
        final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
        final String username = tokenizer.nextToken();
        final String password = tokenizer.nextToken();

        //Log Username and password for verification
        logger.info("Username: " + username);
        if (password.length() > 0) {
            logger.info("password: " + new String(new char[password.length()]).replace("\0", "*"));
        } else {
            logger.info("password: <none>");
        }

        //Verify user access
        if (method.isAnnotationPresent(RolesAllowed.class)) {
            RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
            Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));

            //Is user valid?
            if (!isUserAllowed(username, password, rolesSet)) {
                requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(AuthenticationRequestFilter.ERROR_ACCESS_DENIED).build());
                return;
            }
        }
    }
}
 
Example 19
Source File: TokenSecurityContextFilter.java    From openscoring with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	SecurityContext requestSecurityContext = requestContext.getSecurityContext();

	SecurityContext securityContext = new SecurityContext(){

		@Override
		public Principal getUserPrincipal(){
			return Anonymous.INSTANCE;
		}

		@Override
		public boolean isUserInRole(String role){
			String token = getToken();

			String roleToken;

			switch(role){
				case Roles.USER:
					roleToken = getUserToken();
					break;
				case Roles.ADMIN:
					roleToken = getAdminToken();
					break;
				default:
					return false;
			}

			return (roleToken).equals(token) || (roleToken).equals("");
		}

		@Override
		public boolean isSecure(){
			return requestSecurityContext != null && requestSecurityContext.isSecure();
		}

		@Override
		public String getAuthenticationScheme(){
			return "TOKEN";
		}

		private String getToken(){
			Map<String, Cookie> cookies = requestContext.getCookies();
			MultivaluedMap<String, String> headers = requestContext.getHeaders();

			Cookie tokenCookie = cookies.get("token");
			if(tokenCookie != null){
				return tokenCookie.getValue();
			}

			String authorizationHeader = headers.getFirst(HttpHeaders.AUTHORIZATION);
			if(authorizationHeader != null && authorizationHeader.startsWith("Bearer ")){
				return authorizationHeader.substring("Bearer ".length());
			}

			return null;
		}
	};

	requestContext.setSecurityContext(securityContext);
}
 
Example 20
Source File: SecurityInterceptor.java    From maven-framework-project with MIT License 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) {
	ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext
			.getProperty("org.jboss.resteasy.core.ResourceMethodInvoker");
	Method method = methodInvoker.getMethod();
	// Access allowed for all
	if (!method.isAnnotationPresent(PermitAll.class)) {
		// Access denied for all
		if (method.isAnnotationPresent(DenyAll.class)) {
			requestContext.abortWith(ACCESS_FORBIDDEN);
			return;
		}

		// Get request headers
		final MultivaluedMap<String, String> headersMap = requestContext.getHeaders();

		// Fetch authorization header
		final List<String> authorization = headersMap.get(AUTHORIZATION_PROPERTY);

		// If no authorization information present; block access
		if (authorization == null || authorization.isEmpty()) {
			requestContext.abortWith(ACCESS_DENIED);
			return;
		}

		// Get encoded username and password
		final String encodedUserPassword = authorization.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", "");

		// Decode username and password
		String usernameAndPassword = new String(Base64.decodeBase64(encodedUserPassword));

		// Split username and password tokens
		final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
		final String username = tokenizer.nextToken();
		final String password = tokenizer.nextToken();

		// Verify user access
		if (method.isAnnotationPresent(RolesAllowed.class)) {
			RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
			Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));

			// Is user valid?
			if (!isUserAllowed(username, password, rolesSet)) {
				requestContext.abortWith(ACCESS_DENIED);
				return;
			}
		}
	}
}