public static Filter general(AuthorizationCodeResourceDetails client, ResourceServerProperties resourceServerProperties, String path, OAuth2ClientContext oauth2ClientContext) { OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationFilter = new OAuth2ClientAuthenticationProcessingFilter(path){ protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { super.successfulAuthentication(request, response, chain, authResult); OAuth2AccessToken accessToken = restTemplate.getAccessToken(); log.warn(new Gson().toJson(authResult)); log.warn(new Gson().toJson(accessToken)); } }; OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(client, oauth2ClientContext); oAuth2ClientAuthenticationFilter.setRestTemplate(oAuth2RestTemplate); UserInfoTokenServices tokenServices = new UserInfoTokenServices(resourceServerProperties.getUserInfoUri(), client.getClientId()); tokenServices.setRestTemplate(oAuth2RestTemplate); oAuth2ClientAuthenticationFilter.setTokenServices(tokenServices); return oAuth2ClientAuthenticationFilter; }
@Bean public FilterRegistrationBean correlationIdFilter() { return new FilterRegistrationBean(new Filter() { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); } @Override public void destroy() { } }); }
@Override public void start(BundleContext context) throws Exception { log.info("######################################################"); log.info("start"); log.info("######################################################"); Hashtable<String, String> props = new Hashtable<>(); props.put("osgi.http.whiteboard.servlet.pattern", "/*"); props.put("init.message", "Crazy filter!"); props.put("service.ranking", "1"); serviceRegistration = context.registerService(Filter.class.getName(), new CrazyFilter(), props); final ServiceReference<?> httpRef = context.getServiceReference("org.osgi.service.http.HttpService"); httpService = (HttpService) context.getService(httpRef); httpService.registerServlet("/foo", new FooServlet(), new Hashtable(), httpService.createDefaultHttpContext()); }
/** * 对过滤器进行调整 * * @param securityManager * @return */ @Bean(name = "shiroFilter") protected ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager, Config config) { ShiroFilterFactoryBean filterFactoryBean = super.shiroFilterFactoryBean(); filterFactoryBean.setSecurityManager(securityManager); //过滤器设置 Map<String, Filter> filters = new HashMap<>(); SecurityFilter securityFilter = new SecurityFilter(); securityFilter.setClients("cas,rest,jwt"); securityFilter.setConfig(config); filters.put("casSecurityFilter", securityFilter); CallbackFilter callbackFilter = new CallbackFilter(); callbackFilter.setConfig(config); filters.put("callbackFilter", callbackFilter); filterFactoryBean.setFilters(filters); return filterFactoryBean; }
/** * Notify all lifecycle event listeners that a particular event has * occurred for this Container. The default implementation performs * this notification synchronously using the calling thread. * * @param type Event type * @param filter The relevant Filter for this event * @param request The servlet request we are processing * @param response The servlet response we are processing */ public void fireInstanceEvent(String type, Filter filter, ServletRequest request, ServletResponse response) { if (listeners.length == 0) return; InstanceEvent event = new InstanceEvent(wrapper, filter, type, request, response); InstanceListener interested[] = null; synchronized (listeners) { interested = (InstanceListener[]) listeners.clone(); } for (int i = 0; i < interested.length; i++) interested[i].instanceEvent(event); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException { // Lazily initialize the delegate if necessary. Filter delegateToUse = this.delegate; if (delegateToUse == null) { synchronized (this.delegateMonitor) { if (this.delegate == null) { WebApplicationContext wac = findWebApplicationContext(); if (wac == null) { throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?"); } this.delegate = initDelegate(wac); } delegateToUse = this.delegate; } } // Let the delegate perform the actual doFilter operation. invokeDelegate(delegateToUse, request, response, filterChain); }
@Test public void testMissingHostname() throws Exception { ServletRequest request = Mockito.mock(ServletRequest.class); Mockito.when(request.getRemoteAddr()).thenReturn(null); ServletResponse response = Mockito.mock(ServletResponse.class); final AtomicBoolean invoked = new AtomicBoolean(); FilterChain chain = new FilterChain() { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException { assertTrue(HostnameFilter.get().contains("???")); invoked.set(true); } }; Filter filter = new HostnameFilter(); filter.init(null); assertNull(HostnameFilter.get()); filter.doFilter(request, response, chain); assertTrue(invoked.get()); assertNull(HostnameFilter.get()); filter.destroy(); }
/** * Perform work as a particular <code>Subject</code>. Here the work will be * granted to a <code>null</code> subject. * * @param methodName * the method to apply the security restriction * @param targetObject * the <code>Filter</code> on which the method will be called. * @param targetParameterTypes * <code>Class</code> array used to instantiate a * <code>Method</code> object. * @param targetParameterValues * <code>Object</code> array contains the runtime parameters * instance. * @param principal * the <code>Principal</code> to which the security privilege * apply */ public static void doAsPrivilege(final String methodName, final Filter targetObject, final Class<?>[] targetParameterTypes, final Object[] targetParameterValues, Principal principal) throws java.lang.Exception { // CometFilter instances must not be cached as Filter or // NoSuchMethodException will be thrown. Class<? extends Filter> targetType = targetObject instanceof CometFilter ? CometFilter.class : Filter.class; Method method = null; Method[] methodsCache = classCache.get(Filter.class); if (methodsCache == null) { method = createMethodAndCacheIt(methodsCache, targetType, methodName, targetParameterTypes); } else { method = findMethod(methodsCache, methodName); if (method == null) { method = createMethodAndCacheIt(methodsCache, targetType, methodName, targetParameterTypes); } } execute(method, targetObject, targetParameterValues, principal); }
private void test(String method, String operation, String contentType, boolean upload, boolean error) throws Exception { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.reset(request); Mockito.when(request.getMethod()).thenReturn(method); Mockito.when(request.getParameter(HttpFSFileSystem.OP_PARAM)).thenReturn(operation); Mockito.when(request.getParameter(HttpFSParametersProvider.DataParam.NAME)). thenReturn(Boolean.toString(upload)); Mockito.when(request.getContentType()).thenReturn(contentType); FilterChain chain = Mockito.mock(FilterChain.class); Filter filter = new CheckUploadContentTypeFilter(); filter.doFilter(request, response, chain); if (error) { Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse.SC_BAD_REQUEST), Mockito.contains("Data upload")); } else { Mockito.verify(chain).doFilter(request, response); } }
public FilterInfo(final String name, final Class<? extends Filter> filterClass) { if (name == null) { throw UndertowServletMessages.MESSAGES.paramCannotBeNull("name"); } if (filterClass == null) { throw UndertowServletMessages.MESSAGES.paramCannotBeNull("filterClass", "Filter", name); } if (!Filter.class.isAssignableFrom(filterClass)) { throw UndertowServletMessages.MESSAGES.filterMustImplementFilter(name, filterClass); } try { final Constructor<Filter> ctor = (Constructor<Filter>) filterClass.getDeclaredConstructor(); ctor.setAccessible(true); this.instanceFactory = new ConstructorInstanceFactory<>(ctor); this.name = name; this.filterClass = filterClass; } catch (NoSuchMethodException e) { throw UndertowServletMessages.MESSAGES.componentMustHaveDefaultConstructor("Filter", filterClass); } }
@Bean public Filter ssoFilter(ClientResources client, String path) { MappingJackson2HttpMessageConverter customJsonMessageConverter = new MappingJackson2HttpMessageConverter(); customJsonMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.TEXT_PLAIN)); MyOAuth2ClientAuthenticationProcessingFilter filter = new MyOAuth2ClientAuthenticationProcessingFilter(path); filter.setAllowSessionCreation(true); MyOAuth2RestTemplate template = new MyOAuth2RestTemplate(client.getClient(), oauth2ClientContext); template.setMessageConverters(Arrays.asList(customJsonMessageConverter)); filter.setRestTemplate(template); MyUserInfoTokenServices tokenServices = new MyUserInfoTokenServices(client.getResource().getUserInfoUri(), client.getClient().getClientId(), userService, userWechatService, userPrivilegeService, privilegeConfigService); tokenServices.setRestTemplate(template); filter.setTokenServices(tokenServices); return filter; }
@Override @SuppressWarnings("unchecked") // doPrivileged() returns the correct type public <T extends Filter> T createFilter(Class<T> c) throws ServletException { if (SecurityUtil.isPackageProtectionEnabled()) { try { return (T) invokeMethod(context, "createFilter", new Object[] { c }); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (t instanceof ServletException) { throw (ServletException) t; } return null; } } else { return context.createFilter(c); } }
@Override protected void before() throws Throwable { originalConfigLocation = System.getProperty("spring.config.location"); if (!StringUtils.isEmpty(configurationLocation)) { System.setProperty("spring.config.location", configurationLocation); } app = new SpringApplication(LocalTestDataFlowServer.class); configurableApplicationContext = (WebApplicationContext) app.run(new String[]{"--server.port=0"}); Collection<Filter> filters = configurableApplicationContext.getBeansOfType(Filter.class).values(); mockMvc = MockMvcBuilders.webAppContextSetup(configurableApplicationContext) .addFilters(filters.toArray(new Filter[filters.size()])) .build(); dataflowPort = configurableApplicationContext.getEnvironment().resolvePlaceholders("${server.port}"); }
@Override protected void before() throws Throwable { final SpringApplicationBuilder builder = new SpringApplicationBuilder(LocalTestSkipperServer.class); if (this.configLocations != null && this.configLocations.length > 0) { builder.properties( String.format("spring.config.location:%s", StringUtils.arrayToCommaDelimitedString(this.configLocations)) ); } if (this.configNames != null && this.configNames.length > 0) { builder.properties( String.format("spring.config.name:%s", StringUtils.arrayToCommaDelimitedString(this.configNames)) ); } this.app = builder.build(); configurableApplicationContext = app.run( new String[] { "--server.port=0" }); Collection<Filter> filters = configurableApplicationContext.getBeansOfType(Filter.class).values(); mockMvc = MockMvcBuilders.webAppContextSetup((WebApplicationContext) configurableApplicationContext) .addFilters(filters.toArray(new Filter[filters.size()])).build(); skipperPort = configurableApplicationContext.getEnvironment().resolvePlaceholders("${server.port}"); }
@Bean(name = "shiroFilter") public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager, CasConfig casConfig, CasFilter casFilter){ ShiroFilterFactoryBean factoryBean = new MyShiroFilterFactoryBean(); factoryBean.setSecurityManager(securityManager); factoryBean.setLoginUrl(casConfig.getLocalServerLoginUrl()); factoryBean.setSuccessUrl("/user"); factoryBean.setUnauthorizedUrl("/403"); // 添加casFilter到shiroFilter中 Map<String, Filter> filterMap = new HashMap<String, Filter>(1); filterMap.put(CAS_FILTER, casFilter); factoryBean.setFilters(filterMap); loadShiroFilterChain(factoryBean, casConfig); return factoryBean; }
@Override public void doFilter(final ServletRequest request, final ServletResponse response) throws IOException, ServletException { if (currentPosition == additionalFilters.size()) { originalChain.doFilter(request, response); } else { currentPosition++; Filter nextFilter = additionalFilters.get(currentPosition - 1); nextFilter.doFilter(request, response, this); } }
/** * Web服务过滤器 * * @return */ @Override protected Filter[] getServletFilters() { //所有内容按UTF-8编码 CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding("UTF-8"); encodingFilter.setForceEncoding(true); //跨域访问支持 Filter corsfilter = new CORSFilter(); return new Filter[]{encodingFilter, corsfilter}; }
@Bean public FilterRegistrationBean threadLocalFilter() { Filter filter = new MDCServletFilter(); FilterRegistrationBean registration = new FilterRegistrationBean(filter); registration.setOrder(Ordered.HIGHEST_PRECEDENCE); registration.setName(MDCServletFilter.class.getSimpleName()); return registration; }
@Bean("shiroFilter") public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) { ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean(); shiroFilter.setSecurityManager(securityManager); //oauth过滤 Map<String, Filter> filters = new HashMap<>(); filters.put("oauth2", new OAuth2Filter()); shiroFilter.setFilters(filters); Map<String, String> filterMap = new LinkedHashMap<>(); filterMap.put("/webjars/**", "anon"); filterMap.put("/druid/**", "anon"); filterMap.put("/api/**", "anon"); //swagger配置 filterMap.put("/swagger**", "anon"); filterMap.put("/v2/api-docs", "anon"); filterMap.put("/swagger-resources/configuration/ui", "anon"); filterMap.put("/sys/login", "anon"); filterMap.put("/**/*.css", "anon"); filterMap.put("/**/*.js", "anon"); filterMap.put("/**/*.html", "anon"); filterMap.put("/fonts/**", "anon"); filterMap.put("/plugins/**", "anon"); filterMap.put("/favicon.ico", "anon"); filterMap.put("/captcha.jpg", "anon"); filterMap.put("/", "anon"); filterMap.put("/**", "oauth2"); shiroFilter.setFilterChainDefinitionMap(filterMap); return shiroFilter; }
@Override public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) { if (SecurityUtil.isPackageProtectionEnabled()) { return (FilterRegistration.Dynamic) doPrivileged("addFilter", new Class[]{String.class, Filter.class}, new Object[]{filterName, filter}); } else { return context.addFilter(filterName, filter); } }
/** * Perform work as a particular <code>Subject</code>. Here the work * will be granted to a <code>null</code> subject. * * @param methodName the method to apply the security restriction * @param targetObject the <code>Filter</code> on which the method will * be called. * @param targetParameterTypes <code>Class</code> array used to instantiate a * <code>Method</code> object. * @param targetParameterValues <code>Object</code> array contains the * runtime parameters instance. * @param principal the <code>Principal</code> to which the security * privilege apply */ public static void doAsPrivilege(final String methodName, final Filter targetObject, final Class<?>[] targetParameterTypes, final Object[] targetParameterValues, Principal principal) throws java.lang.Exception{ // CometFilter instances must not be cached as Filter or // NoSuchMethodException will be thrown. Class<? extends Filter> targetType = targetObject instanceof CometFilter ? CometFilter.class : Filter.class; Method method = null; Method[] methodsCache = classCache.get(Filter.class); if(methodsCache == null) { method = createMethodAndCacheIt(methodsCache, targetType, methodName, targetParameterTypes); } else { method = findMethod(methodsCache, methodName); if (method == null) { method = createMethodAndCacheIt(methodsCache, targetType, methodName, targetParameterTypes); } } execute(method, targetObject, targetParameterValues, principal); }
/** * Construct a new InstanceEvent with the specified parameters. This * constructor is used for filter lifecycle events. * * @param wrapper Wrapper managing this servlet instance * @param filter Filter instance for which this event occurred * @param type Event type (required) * @param exception Exception that occurred */ public InstanceEvent(Wrapper wrapper, Filter filter, String type, Throwable exception) { super(wrapper); this.filter = filter; this.servlet = null; this.type = type; this.exception = exception; }
/** * Construct a new InstanceEvent with the specified parameters. This * constructor is used for filter processing events. * * @param wrapper Wrapper managing this servlet instance * @param filter Filter instance for which this event occurred * @param type Event type (required) * @param request Servlet request we are processing * @param response Servlet response we are processing */ public InstanceEvent(Wrapper wrapper, Filter filter, String type, ServletRequest request, ServletResponse response) { super(wrapper); this.filter = filter; this.servlet = null; this.type = type; this.request = request; this.response = response; }
/** * Construct a new InstanceEvent with the specified parameters. This * constructor is used for filter processing events. * * @param wrapper Wrapper managing this servlet instance * @param filter Filter instance for which this event occurred * @param type Event type (required) * @param request Servlet request we are processing * @param response Servlet response we are processing * @param exception Exception that occurred */ public InstanceEvent(Wrapper wrapper, Filter filter, String type, ServletRequest request, ServletResponse response, Throwable exception) { super(wrapper); this.filter = filter; this.servlet = null; this.type = type; this.request = request; this.response = response; this.exception = exception; }
/** * 对过滤器进行调整 * * @param securityManager * @return */ @Bean protected ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager, SubjectFactory subjectFactory,@Qualifier("filters") Map<String, Filter> filters) { //把subject对象设为subjectFactory ((DefaultSecurityManager) securityManager).setSubjectFactory(subjectFactory); ShiroFilterFactoryBean filterFactoryBean = super.shiroFilterFactoryBean(); filterFactoryBean.setSecurityManager(securityManager); filterFactoryBean.setFilters(filters); return filterFactoryBean; }
/** * Notify all lifecycle event listeners that a particular event has * occurred for this Container. The default implementation performs * this notification synchronously using the calling thread. * * @param type Event type * @param filter The relevant Filter for this event * @param request The servlet request we are processing * @param response The servlet response we are processing */ public void fireInstanceEvent(String type, Filter filter, ServletRequest request, ServletResponse response) { if (listeners.length == 0) return; InstanceEvent event = new InstanceEvent(wrapper, filter, type, request, response); InstanceListener interested[] = listeners; for (int i = 0; i < interested.length; i++) interested[i].instanceEvent(event); }
LifecyleInterceptorInvocation(List<LifecycleInterceptor> list, FilterInfo filterInfo, Filter filter, FilterConfig filterConfig) { this.list = list; this.servlet = null; this.servletConfig = null; this.filter = filter; this.filterConfig = filterConfig; this.filterInfo = filterInfo; this.servletInfo = null; i = list.size(); }
@Override public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) { if (SecurityUtil.isPackageProtectionEnabled()) { return (FilterRegistration.Dynamic) doPrivileged("addFilter", new Class[]{String.class, Class.class}, new Object[]{filterName, filterClass}); } else { return context.addFilter(filterName, filterClass); } }
/** * Construct a new InstanceEvent with the specified parameters. This * constructor is used for filter lifecycle events. * * @param wrapper Wrapper managing this servlet instance * @param filter Filter instance for which this event occurred * @param type Event type (required) * @param exception Exception that occurred */ public InstanceEvent(Wrapper wrapper, Filter filter, String type, Throwable exception) { super(wrapper); this.wrapper = wrapper; this.filter = filter; this.servlet = null; this.type = type; this.exception = exception; }
public void init( FilterConfig filterConfig) throws ServletException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) _LOG.severe("CANNOT_FIND_CONTEXT_CLASS_LOADER"); else { try { Class<?> proxiedClass = loader.loadClass( "org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl"); _proxied = (Filter) proxiedClass.newInstance(); _proxied.init(filterConfig); } catch (ClassNotFoundException cnfe) { _LOG.severe(cnfe); } catch (IllegalAccessException iae) { _LOG.severe(iae); } catch (InstantiationException ie) { _LOG.severe(ie); } catch (RuntimeException e) { // OC4J was not reporting these errors properly: _LOG.severe(e); throw e; } } }
@Override protected Filter[] getServletFilters() { final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter(); encodingFilter.setEncoding(CHARACTER_ENCODING); encodingFilter.setForceEncoding(true); return new Filter[]{encodingFilter}; }
private Filter filter(String className) { Class clazz = null; try { clazz = Class.forName(className); Object obj = clazz.newInstance(); return (Filter) obj; } catch (Exception e) { throw new RuntimeException("instance filter fail", e); } }
private Filter ssoFilter() { CompositeFilter filter = new CompositeFilter(); List<Filter> filters = new ArrayList<>(); ClientResources github = github(); filters.add(ssoFilter(github, "/login/github", new OAuth2RestTemplate(github.getClient(), oauth2ClientContext))); ClientResources sina = sina(); filters.add(sinaSsoFilter(sina, new OAuth2RestTemplate(sina.getClient(), oauth2ClientContext))); filters.add(qqSsoFilter(qq())); filter.setFilters(filters); return filter; }
private Filter qqSsoFilter(ClientResources client) { QQOAuth2RestTemplate oAuth2RestTemplate = new QQOAuth2RestTemplate(client.getClient(), oauth2ClientContext); OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/qq"); oAuth2ClientAuthenticationFilter.setRestTemplate(oAuth2RestTemplate); QQUserInfoTokenServices tokenServices = new QQUserInfoTokenServices(client.getResource().getUserInfoUri(), client.getClient().getClientId()); tokenServices.setUserService(userService); tokenServices.setRestTemplate(oAuth2RestTemplate); oAuth2ClientAuthenticationFilter.setTokenServices(tokenServices); return oAuth2ClientAuthenticationFilter; }
private Filter sinaSsoFilter(ClientResources client, OAuth2RestTemplate oAuth2RestTemplate) { OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/sina"); oAuth2ClientAuthenticationFilter.setRestTemplate(oAuth2RestTemplate); SinaUserInfoTokenServices tokenServices = new SinaUserInfoTokenServices(client.getResource().getUserInfoUri(), client.getClient().getClientId()); tokenServices.setUserService(userService); tokenServices.setRestTemplate(oAuth2RestTemplate); oAuth2ClientAuthenticationFilter.setTokenServices(tokenServices); return oAuth2ClientAuthenticationFilter; }
@Override public FilterRegistration.Dynamic addFilter(final String filterName, final Filter filter) { ensureNotProgramaticListener(); ensureNotInitialized(); if (deploymentInfo.getFilters().containsKey(filterName)) { return null; } FilterInfo f = new FilterInfo(filterName, filter.getClass(), new ImmediateInstanceFactory<>(filter)); deploymentInfo.addFilter(f); deployment.getFilters().addFilter(f); return new FilterRegistrationImpl(f, deployment, this); }
LifecyleInterceptorInvocation(List<LifecycleInterceptor> list, FilterInfo filterInfo, Filter filter) { this.list = list; this.servlet = null; this.servletConfig = null; this.filter = filter; this.filterConfig = null; this.filterInfo = filterInfo; this.servletInfo = null; i = list.size(); }