@Override public URL getRequestURL() { try { return context.getUriInfo().getRequestUri().toURL(); } catch (MalformedURLException ex) { Logger.getLogger(OAuthServerRequest.class.getName()).log(Level.SEVERE, null, ex); return null; } }
@Override public void filter(ContainerRequestContext rc) { String maybeType = rc.getUriInfo().getQueryParameters().getFirst("type"); if (maybeType != null && maybeType.equals("gpx")) { rc.getHeaders().putSingle(HttpHeaders.ACCEPT, "application/gpx+xml"); } }
@Override public void filter(final ContainerRequestContext requestContext) throws IOException { String credentials = getCredentials(requestContext.getHeaders().getFirst(HttpHeaders.AUTHORIZATION)); // If Authorization header is not used, check query parameter where token can be passed as well if (credentials == null) { credentials = requestContext.getUriInfo().getQueryParameters().getFirst(OAUTH_ACCESS_TOKEN_PARAM); } if (!authenticate(requestContext, credentials, SecurityContext.BASIC_AUTH)) { throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm)); } }
@Override public Set<String> getParameterNames() { HashSet<String> n = new HashSet<String>(); n.addAll(keys(context.getUriInfo().getQueryParameters())); n.addAll(keys(formParams.get())); return n; }
@Override public List<String> getParameterValues(String name) { ArrayList<String> v = new ArrayList<String>(); v.addAll(values(context.getUriInfo().getQueryParameters(), name)); v.addAll(values(formParams.get(), name)); return v; }
/** * The term 'definition method' used by the Jersey model means the method that contains JAX-RS/Jersey annotations. */ private Method getDefinitionMethod(ContainerRequestContext requestContext) { if (!(requestContext.getUriInfo() instanceof ExtendedUriInfo)) { throw new IllegalStateException("Could not get Extended Uri Info. Incompatible version of Jersey?"); } ExtendedUriInfo uriInfo = (ExtendedUriInfo) requestContext.getUriInfo(); ResourceMethod matchedResourceMethod = uriInfo.getMatchedResourceMethod(); Invocable invocable = matchedResourceMethod.getInvocable(); return invocable.getDefinitionMethod(); }
/** * The term 'definition method' used by the Jersey model means the method that contains JAX-RS/Jersey annotations. */ static Method getDefinitionMethod(ContainerRequestContext requestContext) { if (!(requestContext.getUriInfo() instanceof ExtendedUriInfo)) { throw new IllegalStateException("Could not get Extended Uri Info. Incompatible version of Jersey?"); } ExtendedUriInfo uriInfo = (ExtendedUriInfo) requestContext.getUriInfo(); ResourceMethod matchedResourceMethod = uriInfo.getMatchedResourceMethod(); Invocable invocable = matchedResourceMethod.getInvocable(); return invocable.getDefinitionMethod(); }
/** * Name is generated from path as {http-method}:{request-path}. * * @param requestContext context to extract information from * @return name of span to use */ public static String httpPathMethodName(ContainerRequestContext requestContext) { String path = requestContext.getUriInfo().getPath(); if (!path.startsWith("/")) { path = "/" + path; } return requestContext.getMethod() + ":" + path; }
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { final String method = requestContext.getMethod(); final String uri = requestContext.getUriInfo().getRequestUri().toString(); final int respStatus = responseContext.getStatus(); final String reasonPhrase = responseContext.getStatusInfo().getReasonPhrase(); final String srcIpAddr = request.get().getRemoteAddr(); final String contentType = requestContext.getHeaderString(HttpHeaders.CONTENT_TYPE); LOGGER.info("Handled request from {} {} {}, content-type {} status code {} {}", srcIpAddr, method, uri, contentType, respStatus, reasonPhrase); } }
/** * This method checks path of the incoming request, and * redirects following URIs: * <li>/controller -> SiteToSiteResource * @param requestContext request to be modified */ @Override public void filter(ContainerRequestContext requestContext) throws IOException { final UriInfo uriInfo = requestContext.getUriInfo(); if (uriInfo.getPath().equals("controller")){ UriBuilder builder = UriBuilder.fromUri(uriInfo.getBaseUri()) .path(SiteToSiteResource.class) .replaceQuery(uriInfo.getRequestUri().getRawQuery()); URI redirectTo = builder.build(); requestContext.setRequestUri(uriInfo.getBaseUri(), redirectTo); } } }
final UriInfo uriInfo = containerRequestContext.getUriInfo();
@Override public void filter(final ContainerRequestContext request, final ContainerResponseContext response) throws IOException { String id = request.getHeaderString(REQUEST_ID); if (Strings.isNullOrEmpty(id)) { id = generateRandomUuid().toString(); } logger.trace("method={} path={} request_id={} status={} length={}", request.getMethod(), request.getUriInfo().getPath(), id, response.getStatus(), response.getLength()); response.getHeaders().putSingle(REQUEST_ID, id); }
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { if (LOG.isDebugEnabled()) { try { final String rawQuery = requestContext.getUriInfo().getRequestUri().getRawQuery(); final Date requestDate = requestContext.getDate(); final String userName = RestTools.getUserNameFromRequest(requestContext); final String remoteAddress = RestTools.getRemoteAddrFromRequest(response.getRequest(), trustedProxies); final String userAgent = requestContext.getHeaderString(HttpHeaders.USER_AGENT); LOG.debug("{} {} [{}] \"{} {}{}\" {} {} {}", remoteAddress, userName == null ? "-" : userName, (requestDate == null ? "-" : requestDate), requestContext.getMethod(), requestContext.getUriInfo().getPath(), (rawQuery == null ? "" : "?" + rawQuery), (userAgent == null ? "-" : userAgent), responseContext.getStatus(), responseContext.getLength()); } catch (Exception e) { LOG.error("Error while processing REST API access log", e); } } } }
@Override public void filter(ContainerRequestContext request) throws IOException { // do not filter requests that do not use OAuth authentication String authHeader = request.getHeaderString(OAuth1Parameters.AUTHORIZATION_HEADER); if (authHeader == null || !authHeader.toUpperCase().startsWith(OAuth1Parameters.SCHEME.toUpperCase())) { return; } // do not filter requests that matches to access or token resources final Method handlingMethod = uriInfo.get().getMatchedResourceMethod().getInvocable().getHandlingMethod(); if (handlingMethod.isAnnotationPresent(TokenResource.class) || handlingMethod.getDeclaringClass().isAnnotationPresent(TokenResource.class)) { return; } // do not filter if the request path matches pattern to ignore if (match(ignorePathPattern, request.getUriInfo().getPath())) { return; } OAuth1SecurityContext sc; try { sc = getSecurityContext(request); } catch (OAuth1Exception e) { if (optional) { return; } else { throw e; } } request.setSecurityContext(sc); }
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { final Response.StatusType responseStatus = responseContext.getStatusInfo(); final String requestPath = requestContext.getUriInfo().getAbsolutePath().getPath(); final List<MediaType> acceptableMediaTypes = requestContext.getAcceptableMediaTypes(); final boolean acceptsHtml = acceptableMediaTypes.stream() .anyMatch(mediaType -> mediaType.isCompatible(MediaType.TEXT_HTML_TYPE) || mediaType.isCompatible(MediaType.APPLICATION_XHTML_XML_TYPE)); final boolean isGetRequest = "get".equalsIgnoreCase(requestContext.getMethod()); if (isGetRequest && responseStatus == Response.Status.NOT_FOUND && acceptsHtml && !requestPath.startsWith("/" + HttpConfiguration.PATH_API)) { final String entity = indexHtmlGenerator.get(requestContext.getHeaders()); responseContext.setStatusInfo(Response.Status.OK); responseContext.setEntity(entity, new Annotation[0], MediaType.TEXT_HTML_TYPE); responseContext.getHeaders().putSingle("X-UA-Compatible", "IE=edge"); } } }
@Override public void filter(final ContainerRequestContext context) throws IOException { final long id = aid.incrementAndGet(); final StringBuilder b = new StringBuilder(); printRequestLine(b, "Server has received a request", id, context.getMethod(), context.getUriInfo() .getRequestUri()); printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getHeaders()); if (printEntity && context.hasEntity()) { context.setEntityStream(logInboundEntity(b, context.getEntityStream())); } log(b); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { final SecurityContext securityContext = requestContext.getSecurityContext(); if (securityContext instanceof ShiroSecurityContext) { final ShiroSecurityContext context = (ShiroSecurityContext) securityContext; final String userName = RestTools.getUserNameFromRequest(requestContext); final ContextAwarePermissionAnnotationHandler annotationHandler = new ContextAwarePermissionAnnotationHandler(context); final String[] requiredPermissions = annotation.value(); try { LOG.debug("Checking authorization for user [{}], needs permissions: {}", userName, requiredPermissions); annotationHandler.assertAuthorized(annotation); } catch (AuthorizationException e) { LOG.info("Not authorized. User <{}> is missing permissions {} to perform <{} {}>", userName, Arrays.toString(requiredPermissions), requestContext.getMethod(), requestContext.getUriInfo().getPath()); throw new ForbiddenException("Not authorized"); } } else { throw new ForbiddenException(); } } }
@Override public void filter(final ContainerRequestContext context) throws IOException { if (!logger.isLoggable(level)) { return; } final long id = _id.incrementAndGet(); context.setProperty(LOGGING_ID_PROPERTY, id); final StringBuilder b = new StringBuilder(); printRequestLine(b, "Server has received a request", id, context.getMethod(), context.getUriInfo().getRequestUri()); printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getHeaders()); if (context.hasEntity() && printEntity(verbosity, context.getMediaType())) { context.setEntityStream( logInboundEntity(b, context.getEntityStream(), MessageUtils.getCharset(context.getMediaType()))); } log(b); }
@Override public void filter(final ContainerRequestContext context) throws IOException { if (!logger.isLoggable(level)) { return; } final long id = _id.incrementAndGet(); context.setProperty(LOGGING_ID_PROPERTY, id); final StringBuilder b = new StringBuilder(); printRequestLine(b, "Server has received a request", id, context.getMethod(), context.getUriInfo().getRequestUri()); printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getHeaders()); if (context.hasEntity() && printEntity(verbosity, context.getMediaType())) { context.setEntityStream( logInboundEntity(b, context.getEntityStream(), MessageUtils.getCharset(context.getMediaType()))); } log(b); }
@Override protected SecurityFilter.FilterContext initRequestFiltering(ContainerRequestContext requestContext) { SecurityFilter.FilterContext context = new SecurityFilter.FilterContext(); // this is a pre-matching filter, so no method or class security SecurityDefinition methodDef = new SecurityDefinition(false); methodDef.requiresAuthentication(true); methodDef.setRequiresAuthorization(featureConfig().shouldUsePrematchingAuthorization()); context.setMethodSecurity(methodDef); context.setResourceName("jax-rs"); context.setMethod(requestContext.getMethod()); context.setHeaders(HttpUtil.toSimpleMap(requestContext.getHeaders())); context.setTargetUri(requestContext.getUriInfo().getRequestUri()); context.setResourcePath(context.getTargetUri().getPath()); context.setJerseyRequest((ContainerRequest) requestContext); // now extract headers featureConfig().getQueryParamHandlers() .forEach(handler -> handler.extract(uriInfo, context.getHeaders())); return context; }