javax.ws.rs.container.ContainerRequestFilter源码实例Demo

类javax.ws.rs.container.ContainerRequestFilter源码实例Demo

下面列出了javax.ws.rs.container.ContainerRequestFilter 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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)));
}
 
@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)));
}
 
源代码3 项目: trellis   文件: TrellisUtilsTest.java
@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!");
}
 
源代码4 项目: jrestless-examples   文件: RequestHandler.java
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();
}
 
源代码5 项目: dropwizard-auth-jwt   文件: JwtAuthProviderTest.java
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();
        }
 
源代码6 项目: sinavi-jfw   文件: LocaleContextFilterTest.java
@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;
}
 
源代码7 项目: cxf   文件: JAXRSUtils.java
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;
}
 
源代码8 项目: cxf   文件: ServerProviderFactory.java
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;
    }
}
 
源代码9 项目: cxf   文件: ServerProviderFactory.java
@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;
}
 
/**
 * 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());
        }
    };
}
 
/**
 * 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()));
        }
    };
}
 
/**
 * 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());
        }
    };
}
 
/**
 * 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()));
        }
    };
}
 
@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)));
}
 
@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)));
}
 
@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)));
}
 
@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)));
}
 
源代码18 项目: java-jaxrs   文件: InstrumentedRestApplication.java
@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);
}
 
源代码19 项目: aries-jax-rs-whiteboard   文件: JaxrsTest.java
@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));
}
 
/**
 * 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();
}
 
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();
}
 
源代码22 项目: cxf   文件: ServerProviderFactory.java
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);
}
 
源代码23 项目: cxf   文件: ServerProviderFactory.java
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);
        }
    }

}
 
源代码24 项目: cxf   文件: ConfigurationImplTest.java
@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));
    }
}
 
源代码25 项目: cxf   文件: ConfigurationImplTest.java
@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));
}
 
源代码26 项目: Singularity   文件: JerseyBinder.java
public static LinkedBindingBuilder<ContainerRequestFilter> bindContainerRequestFilter(
  Binder binder
) {
  Multibinder<ContainerRequestFilter> requestFilterBinder = Multibinder.newSetBinder(
    binder,
    ContainerRequestFilter.class
  );
  return requestFilterBinder.addBinding();
}
 
源代码27 项目: tomee   文件: RESTService.java
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);
}
 
源代码28 项目: jweb-cms   文件: WebConfigImpl.java
@Override
public WebConfig bindRequestFilter(ContainerRequestFilter filter) {
    app.register(filter);
    return this;
}
 
源代码29 项目: jrestless   文件: ApplicationPathFilterTest.java
private static ContainerRequestFilter createApplicationPathFilter(Application app) {
	ApplicationPathFilter filter = new ApplicationPathFilter();
	filter.setApplication(app);
	return filter;
}
 
@Override
public boolean configure(FeatureContext fc) {
    
    Configuration configuration = fc.getConfiguration();
    
    if(_LOG.isInfoEnabled()) {
        @SuppressWarnings("unchecked")
        Map<String, Object> applicationProps = (Map<String, Object>) configuration.getProperty(JAX_RS_APPLICATION_SERVICE_PROPERTIES);
        _LOG.info("Registering the Shiro Authentication feature with application {}", 
                applicationProps.getOrDefault(JAX_RS_NAME, "<No Name found in application configuration>"));
    }
    
    if(realms.isEmpty()) {
        _LOG.warn("There are no authentication realms available. Users may not be able to authenticate.");
    } else {
        _LOG.debug("Using the authentication realms {}.", realms);
    }

    _LOG.debug("Registering the Shiro SecurityManagerAssociatingFilter");
    fc.register(new SecurityManagerAssociatingFilter(manager), AUTHENTICATION);

    Map<Class<?>, Integer> contracts = configuration.getContracts(ExceptionMapper.class);
    if(contracts.isEmpty()) {
        _LOG.debug("Registering the Shiro ExceptionMapper");
        // Only register the ExceptionMapper if it isn't already registered
        fc.register(ExceptionMapper.class, AUTHENTICATION);
    } else if(AUTHENTICATION < contracts.getOrDefault(javax.ws.rs.ext.ExceptionMapper.class, USER)) {
        _LOG.debug("Updating the priority of the Shiro ExceptionMapper from {} to {}",
                contracts.getOrDefault(javax.ws.rs.ext.ExceptionMapper.class, USER),
                AUTHORIZATION);
        // Update the priority if it's registered too low
        contracts.put(javax.ws.rs.ext.ExceptionMapper.class, AUTHENTICATION);
    }

    contracts = configuration.getContracts(SubjectPrincipalRequestFilter.class);
    if(contracts.isEmpty()) {
        _LOG.debug("Registering the Shiro SubjectPrincipalRequestFilter");
        // Only register the SubjectPrincipalRequestFilter if it isn't already registered
        // and make sure it always comes after the SecurityManagerAssociatingFilter
        fc.register(SubjectPrincipalRequestFilter.class, AUTHENTICATION + 1);
    } else if(AUTHENTICATION < contracts.getOrDefault(ContainerRequestFilter.class, USER)) {
        _LOG.debug("Updating the priority of the Shiro SubjectPrincipalRequestFilter from {} to {}",
                contracts.getOrDefault(ContainerRequestFilter.class, USER),
                AUTHENTICATION + 1);
        // Update the priority if it's registered too low
        contracts.put(ContainerRequestFilter.class, AUTHENTICATION + 1);
    }
    
    return true;
}
 
如果文章对您有帮助,请点击页面广告。以鼓励作者做出的努力。
 类所在包
 类方法
 同包方法