@Override public void filter( ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException { MultivaluedMap<String, Object> headers = containerResponseContext.getHeaders(); headers.add( "Access-Control-Allow-Origin", "*"); headers.add( "Access-Control-Allow-Methods", "GET, POST, OPTIONS"); headers.add( "Access-Control-Allow-Headers", "Cache-Control, X-Requested-With, Origin, Content-Type, Accept, Authorization"); }
private void setHeader(String format, ContainerRequestContext containerRequestContext) { ArrayList<String> mediaTypes = new ArrayList<>(); switch (format) { case ("json"): mediaTypes.add(MediaType.APPLICATION_JSON); mediaTypes.add(MediaTypes.LDJSON); break; case ("xml"): mediaTypes.add(MediaType.APPLICATION_XML); mediaTypes.add(MediaTypes.RDFXML); break; case ("ttl"): mediaTypes.add(MediaTypes.TURTLE); break; default: LOG.error("Format parameter {} not supported -> ignored", format); break; } if (!mediaTypes.isEmpty()) { LOG.debug("Format parameter {} set, expand Accept header with {}", format, mediaTypes); containerRequestContext.getHeaders().put(HttpHeaders.ACCEPT, mediaTypes); } }
@Override public void filter(ContainerRequestContext request, ContainerResponseContext response) { String path = request.getUriInfo().getRequestUri().getPath(); LOG.fine(String.format("Received request : crossdomain for %s", path)); // TODO : disable for production // *** ONLY FOR DEMO *** // response.getHeaders().add("Access-Control-Allow-Origin", "http://localhost:3002"); response.getHeaders().add("Access-Control-Allow-Origin", "*"); response.getHeaders().add("Access-Control-Allow-Headers", "Content-Range, Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); response.getHeaders().add("Access-Control-Expose-Headers", "Content-Range, Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); // response.getHeaders().add("Access-Control-Allow-Credentials", "http://localhost:3002"); response.getHeaders().add("Access-Control-Allow-Credentials", "*"); response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH"); response.getHeaders().add("Access-Control-Max-Age", "*"); }
static String extractRequestEntity(ContainerRequestContext request) { if (request.hasEntity()) { InputStream inputStreamOriginal = request.getEntityStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamOriginal, MAX_ENTITY_READ); bufferedInputStream.mark(MAX_ENTITY_READ); byte[] bytes = new byte[MAX_ENTITY_READ]; int read; try { read = bufferedInputStream.read(bytes, 0, MAX_ENTITY_READ); bufferedInputStream.reset(); } catch (IOException e) { throw new RuntimeException(e); } request.setEntityStream(bufferedInputStream); return new String(bytes, Charsets.UTF_8); } return null; }
@Override public void filter(final ContainerRequestContext ctx) throws IOException { final List<String> exts = ctx.getUriInfo().getQueryParameters().getOrDefault("ext", emptyList()); if (exts.contains(UPLOADS)) { if (INVALID_EXT_METHODS.contains(ctx.getMethod())) { ctx.abortWith(status(METHOD_NOT_ALLOWED).build()); } if (ctx.getMethod().equals("POST")) { final String path = ctx.getUriInfo().getPath(); final String urlBase = nonNull(baseUrl) ? baseUrl : ctx.getUriInfo().getBaseUri().toString(); final String contentType = ofNullable(ctx.getMediaType()).map(MediaType::toString) .orElse(APPLICATION_OCTET_STREAM); final String identifier = ofNullable(ctx.getHeaderString("Slug")) .orElseGet(resourceService.getIdentifierSupplier()); final String uploadId = binaryService.initiateUpload(rdf.createIRI(TRELLIS_PREFIX + path + identifier), contentType); if (isNull(uploadId)) { throw new WebApplicationException("Cannot initiate multipart upload", BAD_REQUEST); } ctx.abortWith(status(CREATED).location(create(urlBase + UPLOAD_PREFIX + uploadId)).build()); } } }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { // Get the Authorization header from the request String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION); // Validate the Authorization header if (!isTokenBasedAuthentication(authorizationHeader)) { abortWithUnauthorized(requestContext); } // Extract the token from the Authorization header String token = authorizationHeader .substring(AUTHENTICATION_SCHEME.length()).trim(); try { // Validate the token verifyToken(token); } catch (Exception e) { abortWithUnauthorized(requestContext); } }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { if (alwaysAccept(requestContext)) { return; } String apptokenid = requestContext.getHeaderString(APPTOKENID_HEADER); if (apptokenid == null || apptokenid.trim().isEmpty()) { handleErrorNoAppToken(requestContext); } else { ApplicationToken token = tokenServiceClient.getApptokenById(apptokenid); TokenCheckResult result = applicationTokenAccessValidator.checkApplicationToken(token); if (result != TokenCheckResult.AUTHORIZED) { handleErrorUnauthorized(requestContext, apptokenid, result); } else if (! isAllowedToCallEndpoint(token)) { handleErrorUnauthorizedForEndpoint(requestContext, apptokenid, result); } } }
@SuppressWarnings("rawtypes") @Test public void filter404NoParameter() { final ContainerRequestContext requestContext = Mockito.mock(ContainerRequestContext.class); final ContainerResponseContext responseContext = Mockito.mock(ContainerResponseContext.class); Mockito.when(responseContext.getStatus()).thenReturn(204); final Annotation anno1 = Mockito.mock(Annotation.class); final Annotation anno2 = Mockito.mock(Annotation.class); final Annotation[] annotations = new Annotation[] { anno1, anno2 }; Mockito.when((Class) anno2.annotationType()).thenReturn(OnNullReturn404.class); Mockito.when(responseContext.getEntityAnnotations()).thenReturn(annotations); final UriInfo uriInfo = Mockito.mock(UriInfo.class); final MultivaluedMap<String, String> parameters = new MultivaluedHashMap<>(); Mockito.when(uriInfo.getPathParameters()).thenReturn(parameters); Mockito.when(requestContext.getUriInfo()).thenReturn(uriInfo); filter.filter(requestContext, responseContext); Mockito.verify(responseContext, VerificationModeFactory.atLeastOnce()).setStatus(404); Mockito.verify(responseContext, VerificationModeFactory.atLeastOnce()) .setEntity("{\"code\":\"data\",\"message\":null,\"parameters\":null,\"cause\":null}", annotations, MediaType.APPLICATION_JSON_TYPE); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { String usertokenId = requestContext.getHeaderString(Constants.USERTOKENID_HEADER); if (Strings.isNullOrEmpty(usertokenId)) { return; } UserToken userToken; try { userToken = tokenServiceClient.getUserTokenById(usertokenId); } catch (TokenServiceClientException e) { throw new NotAuthorizedException("UsertokenId: '" + usertokenId + "' not valid", e); } UibBrukerPrincipal brukerPrincipal = UibBrukerPrincipal.ofUserToken(userToken); ImmutableSet<String> tilganger = extractRolesAllowed(userToken, brukerPrincipal.uibBruker); requestContext.setSecurityContext(new AutentiseringsContext(brukerPrincipal, tilganger)); if (authenticatedHandler != null) { authenticatedHandler.handle(requestContext); } }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { Single<Boolean> ret = null; for (Map.Entry<AuthorizingAnnotationHandler, Annotation> authzCheck : authzChecks.entrySet()) { AuthorizingAnnotationHandler handler = authzCheck.getKey(); Annotation authzSpec = authzCheck.getValue(); Single<Boolean> check = handler.assertAuthorized(authzSpec); if(ret == null) ret = check; else ret = ret.zipWith(check, (a, b) -> a && b); } if(ret != null) { PreMatchContainerRequestContext context = (PreMatchContainerRequestContext)requestContext; context.suspend(); ret.subscribe(result -> { if (result) context.resume(); else context.resume(new AuthorizationException("Authorization failed")); }, error -> { context.resume(error); }); } }
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { System.out.println("Response = " + requestContext + " " + responseContext); Long start = concurrentRequests.get(requestContext); concurrentRequests.remove(requestContext); long duration = (System.nanoTime() - start); System.out.println("Duration: " + duration); UriInfo uriInfo = requestContext.getUriInfo(); String ipv4 = extractIpAddress(uriInfo); System.out.println("ipv4 = " + ipv4); String serviceName = extractServiceName(uriInfo); System.out.println("serviceName = " + serviceName); String spanName = extractSpanName(uriInfo); System.out.println("spanName = " + spanName); Optional<String> traceId = extractTraceId(requestContext); String spanId = traceId.map(id -> this.tracee.saveChildSpan(id, spanName, serviceName, ipv4, 0)). orElseGet(() -> this.tracee.saveParentSpan(spanName, serviceName, ipv4, duration)); System.out.println("Storing span id: " + spanId); storeSpandId(responseContext, spanId); }
@Override public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException { MultivaluedMap<String, Object> headers = containerResponseContext.getHeaders(); headers.add(ACCESS_CONTROL_ALLOW_HEADERS, "orgin"); headers.add(ACCESS_CONTROL_ALLOW_HEADERS, "content-type"); headers.add(ACCESS_CONTROL_ALLOW_HEADERS, "accept"); headers.add(ACCESS_CONTROL_ALLOW_HEADERS, "authorization"); customHeaders.forEach(s -> headers.add(ACCESS_CONTROL_ALLOW_HEADERS, s)); // make sure there's only one header with this name String headerString = (String) headers.get(ACCESS_CONTROL_ALLOW_HEADERS).stream() .reduce((a, b) -> a.toString() + ", " + b.toString()).get(); headers.putSingle(ACCESS_CONTROL_ALLOW_HEADERS, headerString); headers.putSingle("Access-Control-Allow-Credentials", "true"); headers.putSingle("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); }
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()); } } } } }
/** * Extracts the body from the supplied request. */ private static void extractBodyParameter(final RequestParameters requestParameters, final ContainerRequestContext ctx, final Optional<Parameter> parameter) throws IOException { String body = extractBody(ctx); if (body == null) { return; } requestParameters.setRawBody(body); if (!parameter.isPresent()) { return; } if (ctx.getHeaders().get(HttpHeaders.CONTENT_TYPE).stream().filter( header -> ContentType.APPLICATION_JSON.toString().startsWith(header)).findAny().orElse( null) == null) { return; } ObjectMapper objectMapper = new ObjectMapper(); Map json = objectMapper.readValue(body, Map.class); if (json.keySet().size() == 1) { requestParameters.putAll(json); } }
@SuppressWarnings("boxing") @Test public void testVersionFilterVersionNotExisting() { try { UriInfo info = mock(UriInfo.class); MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); ContainerRequestContext request = mock( ContainerRequestContext.class); when(info.getPathParameters()).thenReturn(map); when(request.getUriInfo()).thenReturn(info); VersionFilter filter = new VersionFilter(); filter.filter(request); } catch (WebApplicationException e) { assertEquals(Status.NOT_FOUND.getStatusCode(), e.getResponse().getStatus()); } }
@Override public Object provideValue(Parameter parameter, ContainerRequestContext requestContext, ObjectMapper objectMapper) { Object returnValue; String value = requestContext.getHeaderString(parameter.getAnnotation(HeaderParam.class).value()); if (value == null) { return null; } else { if (String.class.isAssignableFrom(parameter.getType())) { returnValue = value; } else { try { returnValue = objectMapper.readValue(value, parameter.getType()); } catch (IOException e) { throw new IllegalStateException(e); } } } return returnValue; }
/** * Extracts body from a provided request context. Note that this method blocks until the body is * not fully read. Also note that it would not be possible to read from the underlying stream * again. {@link IOUtils#copy(InputStream, Writer)} is used. * * @param ctx JAX-RS request context * @return body of the underlying stream or <code>null</code> if the provided request contains no * body * @throws IOException in case of any problems with the underlying stream */ @SuppressWarnings("resource") @Nullable private static String extractBody(ContainerRequestContext ctx) throws IOException { /* * do not use auto-closable construction as it is responsibility of JAX-RS to close the * underlying stream */ IsEmptyCheckInputStream inputStream = new IsEmptyCheckInputStream(ctx.getEntityStream()); if (inputStream.isEmpty()) { return null; } StringWriter writer = new StringWriter(); /* still copy from PushbackStream, not from the underlying stream */ IOUtils.copy(inputStream, writer); return writer.toString(); }
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { UriInfo info = requestContext.getUriInfo(); if (!info.getQueryParameters().containsKey("pretty")) { return; } ObjectWriterInjector.set(new PrettyPrintWriter(ObjectWriterInjector.getAndClear())); }
/** * Filter method called after a response has been provided for a request. * This method will refresh the session of the current token and put in the header with the key Authorization * * @param requestContext request context. * @param responseContext response context. * @throws IOException if an I/O exception occurs. */ @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { if (requestContext.getSecurityContext() != null && requestContext.getSecurityContext().getUserPrincipal() != null) { responseContext.getHeaders().add(HttpHeaders.AUTHORIZATION, this.jwtService.generateToken((JWTPrincipal) requestContext.getSecurityContext().getUserPrincipal()).getToken()); } }
Map<String, String> map(@NonNull InformationProduct informationProduct, @NonNull ContainerRequestContext context) { Map<String, String> result = new HashMap<>(); for (Parameter<?> parameter : informationProduct.getParameters()) { Optional<String> parameterValue = Optional.ofNullable( context.getUriInfo().getQueryParameters().getFirst(parameter.getName())); parameterValue.ifPresent(value -> result.put(parameter.getName(), value)); } return result; }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { try { String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION); String token = authorizationHeader.substring("Bearer".length()).trim(); final Key key = KeyGenerator.getKey(deskDroidService.getApplicationContext()); final JwtParser jwtParser = Jwts.parser().setSigningKey(key); jwtParser.parseClaimsJws(token); } catch (Exception e) { requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build()); } }
private boolean isCorsAllowed(final ContainerRequestContext context) { final String path = context.getUriInfo().getPath(); for (final String corsUrlPattern : pathPrefixes) { if (path.startsWith(corsUrlPattern)) { return true; } } return false; }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { OidcClientTokenContext ctx = (OidcClientTokenContext) JAXRSUtils.getCurrentMessage().getContent(ClientTokenContext.class); IdToken idToken = ctx.getIdToken(); String email = idToken.getEmail(); String hdParam = idToken.getStringProperty("hd"); boolean fromGsuite = config.getGSuiteDomain().equalsIgnoreCase(hdParam); Set<String> externalAccounts = externalAccountsCache.get(); if (!fromGsuite && !externalAccounts.contains(email)) { log.error("Unauthorized access from {}", hdParam); ServerError err = new ServerError("E001", "Sorry you are not allowed to enter this site"); requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(err).type(MediaType.APPLICATION_JSON).build()); } }
public ArrayList<String> getHeadersToLog (ContainerRequestContext request) { ArrayList<String> httpHeaders = new ArrayList<>(); for (String name :request.getHeaders().keySet()) { String authHeaderValue = null; if (name.equals(HttpHeaders.AUTHORIZATION) && StringUtils.isNotBlank(request.getHeaders().get(name).get(0))) { authHeaderValue = request.getHeaders().get(name).get(0); int start = authHeaderValue.length() - AUTH_EXPOSURE_TAIL_SIZE; authHeaderValue = start >= 0 ? authHeaderValue.substring(start, authHeaderValue.length()) : "invalid auth header"; } if (!name.equals(COOKIE_HEADER)) { httpHeaders.add(name + ": " + (authHeaderValue == null ? request.getHeaders().get(name) : authHeaderValue)); } } return httpHeaders; }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { String aboslutePath = requestContext.getUriInfo().getAbsolutePath().toString(); String requestMethod = requestContext.getMethod(); if (aboslutePath.contains("swagger.json") || "OPTIONS".equals(requestMethod)) { return; } if (requireUserToken() && securityContext.getUserPrincipal() == null) { throw new NotAuthorizedException("UsertokenId required"); } }
@Override public void filter(final ContainerRequestContext ctx) throws IOException { final SecurityContext sec = ctx.getSecurityContext(); LOGGER.debug("Checking security context: {}", sec.getUserPrincipal()); if (isNull(sec.getUserPrincipal())) { ctx.setProperty(SESSION_PROPERTY, new HttpSession()); } else if (adminUsers.contains(sec.getUserPrincipal().getName())) { ctx.setProperty(SESSION_PROPERTY, new HttpSession(AdministratorAgent)); } else if (sec.getUserPrincipal().getName().isEmpty()) { ctx.setProperty(SESSION_PROPERTY, new HttpSession()); } else { ctx.setProperty(SESSION_PROPERTY, new HttpSession(agentService.asAgent(sec.getUserPrincipal().getName()))); } }
@Override public void filter(final ContainerRequestContext requestContext) throws IOException { requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { return new Principal() { @Override public String getName() { 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"; } }); }
public boolean allwaysAccept(ContainerRequestContext requestContext) { String aboslutePath = requestContext.getUriInfo().getAbsolutePath().toString(); String requestMethod = requestContext.getMethod(); return aboslutePath.contains("swagger") || "OPTIONS".equals(requestMethod); }
@SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testInterceptor() throws Exception { jwtInterceptor.setClaimsProcessor(new ValidatingProcessor("typ", "https://example.com/register")); final JwtClaims jwtClaims = JwtClaims.parse("{\"typ\":\"https://example.com/register\", \"aud\":\"sample\", \"jti\": \"abc\", \"iss\":\"http://accounts.trajano.net\"}"); final String jwt = cryptoOps.sign(jwtClaims); System.out.println(jwt); final ResourceInfo resourceInfo = Mockito.mock(ResourceInfo.class); Mockito.when(resourceInfo.getResourceMethod()).thenReturn(Hello.class.getMethod("hello2B")); Mockito.when(resourceInfo.getResourceClass()).thenReturn((Class) Hello.class); jwtInterceptor.setResourceInfo(resourceInfo); final ContainerRequestContext containerRequestContext = Mockito.mock(ContainerRequestContext.class); final UriInfo uriInfo = Mockito.mock(UriInfo.class); Mockito.when(uriInfo.getRequestUri()).thenReturn(URI.create("http://trajano.net/sample")); Mockito.when(containerRequestContext.getUriInfo()).thenReturn(uriInfo); Mockito.when(containerRequestContext.getHeaderString("X-JWT-Assertion")).thenReturn(jwt); Mockito.when(containerRequestContext.getHeaderString("X-JWT-Audience")).thenReturn("sample"); mdcInterceptor.filter(containerRequestContext); jwtInterceptor.filter(containerRequestContext); // final Request request = mock(Request.class); // when(request.getHeader("X-JWT-Assertion")).thenReturn(jwt); // final Response responder = mock(Response.class); // final ServiceMethodInfo serviceMethodInfo = mock(ServiceMethodInfo.class); // assertTrue(interceptor.preCall(request, responder, serviceMethodInfo)); }
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { String method = requestContext.getMethod(); logger.debug("Requesting " + method + " for path " + requestContext.getUriInfo().getPath()); Object entity = responseContext.getEntity(); if (entity != null) { logger.debug("Response " + new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(entity)); } }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { // 获取客户端Header中提交的token String token = requestContext.getHeaderString("Authorization"); if (StringUtils.isEmpty(token)) { requestContext.abortWith( Response.status(401).header(HttpHeaders.WWW_AUTHENTICATE, "Barer no auth").entity(ErrorCode.AUTH_FAILED).build()); } // rpc NettyRemotingClient client = RPCServices.getAuthService(); RemotingCommand request = RemotingCommand.createRequestCommand(); request.getExtFields().put("action", "access"); try { RemotingCommand responce = client.invokeSync(request); Boolean access = Boolean.valueOf(responce.getExtFields().get("access")); if (!access) { requestContext.abortWith( Response.status(401).header(HttpHeaders.WWW_AUTHENTICATE, "Barer no auth").entity(ErrorCode.AUTH_FAILED).build()); } } catch (RemotingConnectException | RemotingSendRequestException | RemotingTimeoutException | InterruptedException e) { requestContext.abortWith( Response.status(401).header(HttpHeaders.WWW_AUTHENTICATE, "Barer no auth").entity(ErrorCode.AUTH_FAILED).build()); } }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { final Charset CHARACTER_SET = Charset.forName("utf-8"); String authHeader = requestContext.getHeaders().getFirst(HttpHeaders.AUTHORIZATION); if (authHeader != null && authHeader.startsWith("Basic")) { String decoded = new String(Base64.getDecoder().decode(authHeader.substring(6).getBytes()), CHARACTER_SET); final String[] split = decoded.split(":"); final String username = split[0]; final String password = split[1]; // FIXME: 这里要验证登陆并在请求头或者参数中加入token boolean verify = false; if (!verify) { requestContext.abortWith(Response.status(401).header(HttpHeaders.WWW_AUTHENTICATE, "Basic") .build()); } else { requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { return new Principal() { @Override public String getName() { return username; } }; } @Override public boolean isUserInRole(String role) { return true; } @Override public boolean isSecure() { return false; } @Override public String getAuthenticationScheme() { return "BASIC"; } }); } } }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { if (!serverHealthMonitor.get().isHealthy()) { requestContext.abortWith(Response.status(Response.Status.SERVICE_UNAVAILABLE).entity( serverHealthMonitor.get().getStatus()).build()); } }
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { responseContext.getHeaders().add("X-Powered-By", "Jersey Framework"); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { final HttpSession session = httpServletRequest.getSession(false); if (null == session || null == session.getAttribute(attributeName)) { requestContext.abortWith(Response.seeOther(URI.create("/")).build()); } }
@Override public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext cres) throws IOException { cres.getHeaders().add("Access-Control-Allow-Origin", "*"); cres.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization"); cres.getHeaders().add("Access-Control-Allow-Credentials", "true"); cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); cres.getHeaders().add("Access-Control-Max-Age", "1209600"); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { // Get realm Realm realm = ResourceUtils.lookupResource(getClass(), Realm.class, providers) .orElseThrow(() -> new IOException( "AuthContext setup failed: no Realm available from a ContextResolver or as a Context resource")); // replace SecurityContext requestContext.setSecurityContext( new AuthSecurityContext(realm, HttpUtils.isSecure(requestContext.getUriInfo().getRequestUri()))); }
@Override public void filter(ContainerRequestContext context ) throws IOException { UriInfo uriInfo = context.getUriInfo(); List<PathSegment> pathSegments = uriInfo.getPathSegments(); if(pathSegments != null && !pathSegments.isEmpty()) { // http://memorynotfound.com/jaxrs-path-segments-matrix-parameters/ DomainMarker marker = mdc.createMarker(); for(int i = 0; i < indexes.length; i++) { marker.parseAndSetKey(keys[i], pathSegments.get(indexes[i]).toString()); } marker.pushContext(); } }
@Override public void filter(ContainerRequestContext req, ContainerResponseContext res) throws IOException { res.getHeaders().add("Access-Control-Allow-Origin", "*"); res.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization"); res.getHeaders().add("Access-Control-Allow-Credentials", "true"); res.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD"); }