javax.ws.rs.container.ContainerRequestFilter Java Examples

The following examples show how to use javax.ws.rs.container.ContainerRequestFilter. 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: LocaleContextFilterTest.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
@Override
protected Application configure() {
    enable(TestProperties.LOG_TRAFFIC);
    ResourceConfig config = new ResourceConfig();
    config.register(LocaleContextFilter.class, 1);
    config.register(new ContainerRequestFilter() {

        @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
            called.incrementAndGet();
            locale = LocaleContextKeeper.getLocale();
        }

    }, 2);
    config.register(TestResource.class);
    return config;
}
 
Example #2
Source File: JwtAuthProviderTest.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
protected ContainerRequestFilter getAuthFilter() {

            final JwtConsumer consumer = new JwtConsumerBuilder()
                .setRequireExpirationTime() // the JWT must have an expiration time
                .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew
                .setRequireSubject() // the JWT must have a subject claim
                .setExpectedIssuer("Issuer") // whom the JWT needs to have been issued by
                .setExpectedAudience("Audience") // whom the JWT needs to have been issued by
                .setVerificationKey(new HmacKey(SECRET_KEY.getBytes(UTF_8))) // verify the signature with the public key
                .setRelaxVerificationKeyValidation() // relaxes key length requirement
                .build();// create the JwtConsumer instance

            return new JwtAuthFilter.Builder<>()
                .setCookieName(COOKIE_NAME)
                .setJwtConsumer(consumer)
                .setPrefix(BEARER_PREFIX)
                .setAuthorizer(AuthUtil.getTestAuthorizer(ADMIN_USER, ADMIN_ROLE))
                .setAuthenticator(AuthUtil.getJWTAuthenticator(ImmutableList.of(ADMIN_USER, ORDINARY_USER)))
                .buildAuthFilter();
        }
 
Example #3
Source File: JAXRSUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static boolean runContainerRequestFilters(ServerProviderFactory pf,
                                                 Message m,
                                                 boolean preMatch,
                                                 Set<String> names) throws IOException {
    List<ProviderInfo<ContainerRequestFilter>> containerFilters = preMatch
        ? pf.getPreMatchContainerRequestFilters() : pf.getPostMatchContainerRequestFilters(names);
    if (!containerFilters.isEmpty()) {
        ContainerRequestContext context = new ContainerRequestContextImpl(m, preMatch, false);
        for (ProviderInfo<ContainerRequestFilter> filter : containerFilters) {
            InjectionUtils.injectContexts(filter.getProvider(), filter, m);
            filter.getProvider().filter(context);
            Response response = m.getExchange().get(Response.class);
            if (response != null) {
                setMessageContentType(m, response);
                return true;
            }
        }
    }
    return false;
}
 
Example #4
Source File: ServerProviderFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
private List<ProviderInfo<ContainerRequestFilter>> getContainerRequestFilters(
    List<ProviderInfo<ContainerRequestFilter>> filters, boolean syncNeeded) {

    if (wadlGenerator == null) {
        return filters;
    }
    if (filters.isEmpty()) {
        return Collections.singletonList(wadlGenerator);
    } else if (!syncNeeded) {
        filters.add(0, wadlGenerator);
        return filters;
    } else {
        synchronized (filters) {
            if (filters.get(0) != wadlGenerator) {
                filters.add(0, wadlGenerator);
            }
        }
        return filters;
    }
}
 
Example #5
Source File: BasicAuthSecurityContextFiltersTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Test
public void customPrincipalFunctionUserInfo() throws Exception {
    final Key<String> userInfoKey = newKey("basicPrincipal");
    final ContainerRequestFilter filter = newFilterBuilder(userInfoKey)
            .principalFunction((__, userInfo) -> TEST_USER_INFO.equals(userInfo) ? TEST_PRINCIPAL : null)
            .build();

    filter.filter(requestCtx);
    verifyZeroInteractions(requestCtx);

    AsyncContext.put(userInfoKey, TEST_USER_INFO);
    final ArgumentCaptor<SecurityContext> securityCtxCaptor = ArgumentCaptor.forClass(SecurityContext.class);
    filter.filter(requestCtx);

    verify(requestCtx).setSecurityContext(securityCtxCaptor.capture());
    assertThat(securityCtxCaptor.getValue().getUserPrincipal(), is(sameInstance(TEST_PRINCIPAL)));
}
 
Example #6
Source File: BasicAuthSecurityContextFiltersTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Test
public void customSecurityContextFunctionUserInfo() throws Exception {
    final SecurityContext securityContext = mock(SecurityContext.class);

    final Key<String> userInfoKey = newKey("basicPrincipal");
    final ContainerRequestFilter filter = newFilterBuilder(userInfoKey)
            .securityContextFunction((__, userInfo) -> TEST_USER_INFO.equals(userInfo) ? securityContext : null)
            .build();

    filter.filter(requestCtx);
    verifyZeroInteractions(requestCtx);

    AsyncContext.put(userInfoKey, TEST_USER_INFO);
    final ArgumentCaptor<SecurityContext> securityCtxCaptor = ArgumentCaptor.forClass(SecurityContext.class);
    filter.filter(requestCtx);

    verify(requestCtx).setSecurityContext(securityCtxCaptor.capture());
    assertThat(securityCtxCaptor.getValue(), is(sameInstance(securityContext)));
}
 
Example #7
Source File: ServerProviderFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public Map<Class<?>, Integer> getContracts(Class<?> cls) {
    Map<Class<?>, Integer> map = new HashMap<>();
    if (isRegistered(cls)) {
        if (ContainerRequestFilter.class.isAssignableFrom(cls)) {
            boolean isPreMatch = cls.getAnnotation(PreMatching.class) != null;
            map.put(ContainerRequestFilter.class,
                    getPriority(isPreMatch ? preMatchContainerRequestFilters
                        : postMatchContainerRequestFilters.values(), cls, ContainerRequestFilter.class));
        }
        if (ContainerResponseFilter.class.isAssignableFrom(cls)) {
            map.put(ContainerResponseFilter.class,
                    getPriority(containerResponseFilters.values(), cls, ContainerResponseFilter.class));
        }
        if (WriterInterceptor.class.isAssignableFrom(cls)) {
            map.put(WriterInterceptor.class,
                    getPriority(writerInterceptors.values(), cls, WriterInterceptor.class));
        }
        if (ReaderInterceptor.class.isAssignableFrom(cls)) {
            map.put(ReaderInterceptor.class,
                    getPriority(readerInterceptors.values(), cls, ReaderInterceptor.class));
        }
    }
    return map;
}
 
Example #8
Source File: TrellisUtilsTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testGetAuthFilters() throws Exception {
    final TrellisConfiguration config = new YamlConfigurationFactory<>(TrellisConfiguration.class,
            Validators.newValidator(), Jackson.newMinimalObjectMapper(), "")
        .build(new File(getClass().getResource("/config1.yml").toURI()));
    config.getAuth().getJwt().setKeyStore(null);

    final List<ContainerRequestFilter> filters = TrellisUtils.getAuthFilters(config);
    assertFalse(filters.isEmpty(), "Auth filters are missing!");
    assertEquals(2L, filters.size(), "Incorrect auth filter count!");

    config.getAuth().getBasic().setEnabled(false);
    config.getAuth().getJwt().setEnabled(false);

    assertTrue(TrellisUtils.getAuthFilters(config).isEmpty(), "Auth filters should have been disabled!");
}
 
Example #9
Source File: RequestHandler.java    From jrestless-examples with Apache License 2.0 6 votes vote down vote up
public RequestHandler() {
	// configure the application with the resource
	ResourceConfig config = new ResourceConfig()
			.register(GatewayFeature.class)
			.packages("com.jrestless.aws.examples")
			.register(ApplicationExceptionMapper.class)
			// auto-discovery works, too
			// .register(GlobalExceptionMapper.class)
			.register(new ContainerRequestFilter() {
				@Override
				public void filter(ContainerRequestContext request) throws IOException {
					LOG.info("baseUri: " + request.getUriInfo().getBaseUri());
					LOG.info("requestUri: " + request.getUriInfo().getRequestUri());
				}
			});
	init(config);
	start();
}
 
Example #10
Source File: BasicAuthSecurityContextFilters.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link UserInfoBuilder} instance for building a {@link ContainerRequestFilter} that needs to be
 * globally bound to the JAX-RS {@link Application}.
 *
 * @param userInfoKey the {@link Key} to use to get the user info from {@link AsyncContext}
 * @param <UserInfo> the type of user info object expected in {@link AsyncContext}'s {@code userInfoKey} entry
 * @return a new {@link UserInfoBuilder} instance
 */
public static <UserInfo> UserInfoBuilder<UserInfo> forGlobalBinding(final Key<UserInfo> userInfoKey) {
    //noinspection ResultOfMethodCallIgnored
    requireNonNull(userInfoKey);

    return new UserInfoBuilder<UserInfo>() {
        @Override
        public ContainerRequestFilter build() {
            return new GlobalBindingBasicAuthSecurityContextFilter<>(userInfoKey, securityContextFunction());
        }
    };
}
 
Example #11
Source File: BasicCustomAuthProviderTest.java    From dropwizard-java8 with Apache License 2.0 5 votes vote down vote up
protected ContainerRequestFilter getAuthFilter() {
    BasicCredentialAuthFilter.Builder<Principal> builder = new BasicCredentialAuthFilter.Builder<>();
    builder.setAuthorizer(AuthUtil.getTestAuthorizer(ADMIN_USER, ADMIN_ROLE));
    builder.setAuthenticator(AuthUtil.getBasicAuthenticator(ImmutableList.of(ADMIN_USER, ORDINARY_USER)));
    builder.setPrefix(CUSTOM_PREFIX);
    return builder.buildAuthFilter();
}
 
Example #12
Source File: ServerProviderFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static ProviderInfo<ContainerRequestFilter> createWadlGenerator(Bus bus) {
    Object provider = createProvider(WADL_PROVIDER_NAME, bus);
    if (provider == null) {
        return null;
    }
    return new ProviderInfo<ContainerRequestFilter>((ContainerRequestFilter)provider, bus, true);
}
 
Example #13
Source File: ServerProviderFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void addContainerRequestFilter(
    List<ProviderInfo<ContainerRequestFilter>> postMatchFilters,
    ProviderInfo<ContainerRequestFilter> p) {
    ContainerRequestFilter filter = p.getProvider();
    if (isWadlGenerator(filter.getClass())) {
        wadlGenerator = p;
    } else {
        if (isPrematching(filter.getClass())) {
            addProviderToList(preMatchContainerRequestFilters, p);
        } else {
            postMatchFilters.add(p);
        }
    }

}
 
Example #14
Source File: KeycloakBundle.java    From keycloak-dropwizard-integration with Apache License 2.0 5 votes vote down vote up
/**
 * Default implementation for the Keycloak auth factory. Please provide your own if you implement
 * your own User's representation.
 *
 * @param configuration the application's configuration
 * @return Keycloak auth factory
 */
protected ContainerRequestFilter createAuthFactory(T configuration) {
    return new KeycloakAuthFilter.Builder<Principal>()
            .setConfig(getKeycloakConfiguration(configuration))
            .setAuthenticator(createAuthenticator(getKeycloakConfiguration(configuration)))
            .setAuthorizer(createAuthorizer())
            .setRealm(getRealm(configuration))
            .buildAuthFilter();
}
 
Example #15
Source File: JaxrsTest.java    From aries-jax-rs-whiteboard with Apache License 2.0 5 votes vote down vote up
@Test
public void testPerRequestLifecycleAddon() {
    WebTarget webTarget = createDefaultTarget().path("state");

    assertEquals(0, getRuntimeDTO().applicationDTOs.length);
    assertEquals(0, getRuntimeDTO().failedApplicationDTOs.length);

    ServiceRegistration<?> serviceRegistration = registerAddon(
        new PerRequestTestResource());

    assertEquals("original", webTarget.request().get(String.class));

    registerExtension(
        ContainerRequestFilter.class,
        new PerRequestTestFilter(), "perrequestfilter");

    assertEquals("original-changed", webTarget.request().get(String.class));
    assertEquals(
        "original-changed-changed", webTarget.request().get(String.class));

    serviceRegistration.unregister();

    registerAddonPrototype(PerRequestTestResource::new);

    assertEquals("original-changed", webTarget.request().get(String.class));
    assertEquals("original-changed", webTarget.request().get(String.class));
}
 
Example #16
Source File: ConfigurationImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testServerFilterContractsOnClientIsRejected() {
    try (ConfigurableImpl<Client> configurable 
            = new ConfigurableImpl<>(createClientProxy(), RuntimeType.CLIENT)) {
        Configuration config = configurable.getConfiguration();
        configurable.register(TestFilter.class);
        Map<Class<?>, Integer> contracts = config.getContracts(TestFilter.class);
        assertTrue(contracts.containsKey(ClientRequestFilter.class));
        assertTrue(contracts.containsKey(ClientResponseFilter.class));
        assertFalse(contracts.containsKey(ContainerRequestFilter.class));
        assertFalse(contracts.containsKey(ContainerResponseFilter.class));
    }
}
 
Example #17
Source File: InstrumentedRestApplication.java    From java-jaxrs with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    context.register(new ContainerRequestFilter() {
        @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
            if (requestContext.getUriInfo().getPath().endsWith("filtered")) {
                throw new ForbiddenException();
            }
        }
    }, Priorities.AUTHORIZATION);
}
 
Example #18
Source File: ConfigurationImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testClientFilterContractsOnServerFeatureIsRejected() {
    FeatureContextImpl featureContext = new FeatureContextImpl();
    Configurable<FeatureContext> configurable = new ConfigurableImpl<>(featureContext, RuntimeType.SERVER);
    featureContext.setConfigurable(configurable);
    featureContext.register(TestFilter.class);
    Configuration config = configurable.getConfiguration();
    Map<Class<?>, Integer> contracts = config.getContracts(TestFilter.class);
    assertFalse(contracts.containsKey(ClientRequestFilter.class));
    assertFalse(contracts.containsKey(ClientResponseFilter.class));
    assertTrue(contracts.containsKey(ContainerRequestFilter.class));
    assertTrue(contracts.containsKey(ContainerResponseFilter.class));
}
 
Example #19
Source File: JerseyBinder.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public static LinkedBindingBuilder<ContainerRequestFilter> bindContainerRequestFilter(
  Binder binder
) {
  Multibinder<ContainerRequestFilter> requestFilterBinder = Multibinder.newSetBinder(
    binder,
    ContainerRequestFilter.class
  );
  return requestFilterBinder.addBinding();
}
 
Example #20
Source File: RESTService.java    From tomee with Apache License 2.0 5 votes vote down vote up
private static <T> boolean isProvider(final Class<T> clazz) {
    return MessageBodyReader.class.isAssignableFrom(clazz) ||
            MessageBodyWriter.class.isAssignableFrom(clazz) ||
            ParamConverter.class.isAssignableFrom(clazz) ||
            ContainerRequestFilter.class.isAssignableFrom(clazz) ||
            ContainerResponseFilter.class.isAssignableFrom(clazz) ||
            ReaderInterceptor.class.isAssignableFrom(clazz) ||
            WriterInterceptor.class.isAssignableFrom(clazz) ||
            ParamConverterProvider.class.isAssignableFrom(clazz) ||
            ContextResolver.class.isAssignableFrom(clazz) ||
            Feature.class.isAssignableFrom(clazz) ||
            new MetaAnnotatedClass<>(clazz).isAnnotationPresent(Provider.class);
}
 
Example #21
Source File: BasicAuthSecurityContextFiltersTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Test
public void customSecurityContextFunctionNoUserInfo() throws Exception {
    final SecurityContext securityContext = mock(SecurityContext.class);

    final ContainerRequestFilter filter = newFilterBuilder()
            .securityContextFunction(__ -> securityContext)
            .build();

    final ArgumentCaptor<SecurityContext> securityCtxCaptor = ArgumentCaptor.forClass(SecurityContext.class);
    filter.filter(requestCtx);

    verify(requestCtx).setSecurityContext(securityCtxCaptor.capture());
    assertThat(securityCtxCaptor.getValue(), is(sameInstance(securityContext)));
}
 
Example #22
Source File: BasicAuthSecurityContextFiltersTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Test
public void customPrincipalFunctionNoUserInfo() throws Exception {
    final ContainerRequestFilter filter = newFilterBuilder()
            .principalFunction(__ -> TEST_PRINCIPAL)
            .build();

    final ArgumentCaptor<SecurityContext> securityCtxCaptor = ArgumentCaptor.forClass(SecurityContext.class);
    filter.filter(requestCtx);

    verify(requestCtx).setSecurityContext(securityCtxCaptor.capture());
    assertThat(securityCtxCaptor.getValue().getUserPrincipal(), is(sameInstance(TEST_PRINCIPAL)));
}
 
Example #23
Source File: BasicAuthSecurityContextFiltersTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Test
public void principalUserInfo() throws Exception {
    final Key<Principal> userInfoKey = newKey("basicPrincipal");
    final ContainerRequestFilter filter = newFilterBuilder(userInfoKey).build();

    filter.filter(requestCtx);
    verifyZeroInteractions(requestCtx);

    AsyncContext.put(userInfoKey, TEST_PRINCIPAL);
    final ArgumentCaptor<SecurityContext> securityCtxCaptor = ArgumentCaptor.forClass(SecurityContext.class);
    filter.filter(requestCtx);

    verify(requestCtx).setSecurityContext(securityCtxCaptor.capture());
    assertThat(securityCtxCaptor.getValue().getUserPrincipal(), is(sameInstance(TEST_PRINCIPAL)));
}
 
Example #24
Source File: BasicAuthSecurityContextFiltersTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Test
public void principalNoUserInfo() throws Exception {
    final ContainerRequestFilter filter = newFilterBuilder().build();

    final ArgumentCaptor<SecurityContext> securityCtxCaptor = ArgumentCaptor.forClass(SecurityContext.class);
    filter.filter(requestCtx);

    verify(requestCtx).setSecurityContext(securityCtxCaptor.capture());
    assertThat(securityCtxCaptor.getValue().getUserPrincipal(), is(sameInstance(ANONYMOUS_PRINCIPAL)));
}
 
Example #25
Source File: BasicAuthSecurityContextFilters.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link NoUserInfoBuilder} instance for building a {@link ContainerRequestFilter} that needs to be
 * explicitly bound to resources via the {@link BasicAuthenticated} annotation.
 *
 * @return a new {@link NoUserInfoBuilder} instance
 */
public static NoUserInfoBuilder forNameBinding() {
    return new NoUserInfoBuilder() {
        @Override
        public ContainerRequestFilter build() {
            return new NameBindingBasicAuthSecurityContextFilter<Void>(null,
                    asSecurityContextBiFunction(securityContextFunction()));
        }
    };
}
 
Example #26
Source File: BasicAuthSecurityContextFilters.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link UserInfoBuilder} instance for building a {@link ContainerRequestFilter} that needs to be
 * explicitly bound to resources via the {@link BasicAuthenticated} annotation.
 *
 * @param userInfoKey the {@link Key} to use to get the user info from {@link AsyncContext}
 * @param <UserInfo> the type of user info object expected in {@link AsyncContext}'s {@code userInfoKey} entry
 * @return a new {@link UserInfoBuilder} instance
 */
public static <UserInfo> UserInfoBuilder<UserInfo> forNameBinding(final Key<UserInfo> userInfoKey) {
    //noinspection ResultOfMethodCallIgnored
    requireNonNull(userInfoKey);

    return new UserInfoBuilder<UserInfo>() {
        @Override
        public ContainerRequestFilter build() {
            return new NameBindingBasicAuthSecurityContextFilter<>(userInfoKey, securityContextFunction());
        }
    };
}
 
Example #27
Source File: BasicAuthSecurityContextFilters.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link NoUserInfoBuilder} instance for building a {@link ContainerRequestFilter} that needs to be
 * globally bound to the JAX-RS {@link Application}.
 *
 * @return a new {@link NoUserInfoBuilder} instance
 */
public static NoUserInfoBuilder forGlobalBinding() {
    return new NoUserInfoBuilder() {
        @Override
        public ContainerRequestFilter build() {
            return new GlobalBindingBasicAuthSecurityContextFilter<Void>(null,
                    asSecurityContextBiFunction(securityContextFunction()));
        }
    };
}
 
Example #28
Source File: ServerProviderFactory.java    From cxf with Apache License 2.0 4 votes vote down vote up
public List<ProviderInfo<ContainerRequestFilter>> getPreMatchContainerRequestFilters() {
    return getContainerRequestFilters(preMatchContainerRequestFilters, true);
}
 
Example #29
Source File: ApplicationFeatureTest.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public boolean configure(final FeatureContext featureContext) {
    featureContext.register((ContainerRequestFilter) ctx -> ctx.abortWith(Response.ok("ok").build()));
    return true;
}
 
Example #30
Source File: BasicAuthProviderTest.java    From dropwizard-java8 with Apache License 2.0 4 votes vote down vote up
protected ContainerRequestFilter getAuthFilter() {
    BasicCredentialAuthFilter.Builder<Principal> builder = new BasicCredentialAuthFilter.Builder<>();
    builder.setAuthorizer(AuthUtil.getTestAuthorizer(ADMIN_USER, ADMIN_ROLE));
    builder.setAuthenticator(AuthUtil.getBasicAuthenticator(ImmutableList.of(ADMIN_USER, ORDINARY_USER)));
    return builder.buildAuthFilter();
}