Java Code Examples for javax.servlet.Filter

The following examples show how to use javax.servlet.Filter. These examples are extracted from open source projects. 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 Project: White-Jotter   Source File: ShiroConfiguration.java    License: MIT License 7 votes vote down vote up
@Bean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
    ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
    shiroFilterFactoryBean.setSecurityManager(securityManager);
    shiroFilterFactoryBean.setLoginUrl("/nowhere");

    Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
    Map<String, Filter> customizedFilter = new HashMap<>();  // 自定义过滤器设置 1

    customizedFilter.put("url", getURLPathMatchingFilter()); // 自定义过滤器设置 2,命名,需在设置过滤路径前

    filterChainDefinitionMap.put("/api/authentication", "authc"); // 防鸡贼登录
    filterChainDefinitionMap.put("/api/menu", "authc");
    filterChainDefinitionMap.put("/api/admin/**", "authc");

    filterChainDefinitionMap.put("/api/admin/**", "url");  // 自定义过滤器设置 3,设置过滤路径

    shiroFilterFactoryBean.setFilters(customizedFilter); // 自定义过滤器设置 4,启用
    shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
    return shiroFilterFactoryBean;
}
 
Example 2
Source Project: watchdog-framework   Source File: ShiroConfiguration.java    License: MIT License 6 votes vote down vote up
@Bean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
    log.info("Shiro Configuration initialized");
    ShiroFilterFactoryBean shiroFilterFactoryBean  = new ShiroFilterFactoryBean();

    //设置SecurityManager
    shiroFilterFactoryBean.setSecurityManager(securityManager);
    //拦截器
    //<!-- 过滤链定义,从上向下顺序执行,一般将 /**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了;
    //<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
    Map<String,String> filterChainDefinitionMap = shiroService.getFilterChainDefinitionMap();

    //过滤器
    Map<String,Filter> filters = new HashMap<>();
    filters.put("perms",new JwtFilter());
    shiroFilterFactoryBean.setFilters(filters);
    shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
    return shiroFilterFactoryBean;
}
 
Example 3
Source Project: streamline   Source File: StreamlineApplication.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void addServletFilters(StreamlineConfiguration configuration, Environment environment) {
    List<ServletFilterConfiguration> servletFilterConfigurations = configuration.getServletFilters();
    if (servletFilterConfigurations != null && !servletFilterConfigurations.isEmpty()) {
        for (ServletFilterConfiguration servletFilterConfiguration: servletFilterConfigurations) {
            try {
                addServletFilter(environment, servletFilterConfiguration.getClassName(),
                        (Class<? extends Filter>) Class.forName(servletFilterConfiguration.getClassName()),
                        servletFilterConfiguration.getParams());
            } catch (Exception e) {
                LOG.error("Error occurred while adding servlet filter {}", servletFilterConfiguration);
                throw new RuntimeException(e);
            }
        }
    } else {
        LOG.info("No servlet filters configured");
    }
}
 
Example 4
Source Project: dropwizard-shiro   Source File: ShiroBundle.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create the Shiro filter. Overriding this method allows for complete customization of how Shiro is initialized.
 */
protected Filter createFilter(final T configuration) {
    ShiroConfiguration shiroConfig = narrow(configuration);
    final IniWebEnvironment shiroEnv = new IniWebEnvironment();
    shiroEnv.setConfigLocations(shiroConfig.iniConfigs());
    shiroEnv.init();

    AbstractShiroFilter shiroFilter = new AbstractShiroFilter() {
        @Override
        public void init() throws Exception {
            Collection<Realm> realms = createRealms(configuration);
            WebSecurityManager securityManager = realms.isEmpty()
                    ? shiroEnv.getWebSecurityManager()
                    : new DefaultWebSecurityManager(realms);
            setSecurityManager(securityManager);
            setFilterChainResolver(shiroEnv.getFilterChainResolver());
        }
    };
    return shiroFilter;
}
 
Example 5
Source Project: openwebbeans-meecrowave   Source File: Init.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onStartup(final Set<Class<?>> c, final ServletContext ctx) throws ServletException {
    ctx.addFilter("sci", new Filter() {
        @Override
        public void init(final FilterConfig filterConfig) throws ServletException {
            // no-op
        }

        @Override
        public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
            response.getWriter().write("sci:" + c.stream().map(Class::getName).sorted().collect(joining()));
        }

        @Override
        public void destroy() {
            // no-op
        }
    }).addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/sci");
}
 
Example 6
Source Project: piranha   Source File: NanoPiranha.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Service.
 *
 * @param servletRequest the request.
 * @param servletResponse the response.
 * @throws IOException when an I/O error occurs.
 * @throws ServletException when a Servlet error occurs.
 */
public void service(ServletRequest servletRequest, ServletResponse servletResponse)
        throws IOException, ServletException {
    Iterator<Filter> iterator = filters.descendingIterator();
    NanoFilterChain chain = new NanoFilterChain(servlet);
    while (iterator.hasNext()) {
        Filter filter = iterator.next();
        NanoFilterChain previousChain = chain;
        chain = new NanoFilterChain(filter, previousChain);
    }
    if (servletRequest.getServletContext() == null
            && servletRequest instanceof NanoRequest) {
        NanoRequest nanoRequest = (NanoRequest) servletRequest;
        nanoRequest.setWebApplication(webApplication);
    }
    if (servletResponse instanceof NanoResponse) {
        NanoResponse nanoResponse = (NanoResponse) servletResponse;
        nanoResponse.setWebApplication(webApplication);
    }
    chain.doFilter(servletRequest, servletResponse);
    servletResponse.flushBuffer();
}
 
Example 7
@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}");
}
 
Example 8
Source Project: nomulus   Source File: TestServer.java    License: Apache License 2.0 6 votes vote down vote up
private Context createHandler(
    Map<String, Path> runfiles,
    ImmutableList<Route> routes,
    ImmutableList<Class<? extends Filter>> filters) {
  Context context = new Context(server, CONTEXT_PATH, Context.SESSIONS);
  context.addServlet(new ServletHolder(HealthzServlet.class), "/healthz");
  for (Map.Entry<String, Path> runfile : runfiles.entrySet()) {
    context.addServlet(
        StaticResourceServlet.create(runfile.getKey(), runfile.getValue()),
        runfile.getKey());
  }
  for (Route route : routes) {
    context.addServlet(
        new ServletHolder(wrapServlet(route.servletClass(), filters)), route.path());
  }
  ServletHolder holder = new ServletHolder(DefaultServlet.class);
  holder.setInitParameter("aliases", "1");
  context.addServlet(holder, "/*");
  return context;
}
 
Example 9
Source Project: big-c   Source File: TestHostnameFilter.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 10
Source Project: java-technology-stack   Source File: AbstractMockMvcBuilder.java    License: MIT License 6 votes vote down vote up
/**
 * Build a {@link org.springframework.test.web.servlet.MockMvc} instance.
 */
@Override
@SuppressWarnings("rawtypes")
public final MockMvc build() {
	WebApplicationContext wac = initWebAppContext();
	ServletContext servletContext = wac.getServletContext();
	MockServletConfig mockServletConfig = new MockServletConfig(servletContext);

	for (MockMvcConfigurer configurer : this.configurers) {
		RequestPostProcessor processor = configurer.beforeMockMvcCreated(this, wac);
		if (processor != null) {
			if (this.defaultRequestBuilder == null) {
				this.defaultRequestBuilder = MockMvcRequestBuilders.get("/");
			}
			if (this.defaultRequestBuilder instanceof ConfigurableSmartRequestBuilder) {
				((ConfigurableSmartRequestBuilder) this.defaultRequestBuilder).with(processor);
			}
		}
	}

	Filter[] filterArray = this.filters.toArray(new Filter[0]);

	return super.createMockMvc(filterArray, mockServletConfig, wac, this.defaultRequestBuilder,
			this.globalResultMatchers, this.globalResultHandlers, this.dispatcherServletCustomizers);
}
 
Example 11
Source Project: blog-microservices   Source File: ZuulApplication.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public Filter logFilter() {
    // TODO: Extract bean-def to Util-component!
    CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
    filter.setIncludeQueryString(true);
    filter.setIncludePayload(true);
    filter.setMaxPayloadLength(5120);
    return filter;
}
 
Example 12
Source Project: Spring   Source File: WebInitializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Filter[] getServletFilters() {
    CharacterEncodingFilter cef = new CharacterEncodingFilter();
    cef.setEncoding("UTF-8");
    cef.setForceEncoding(true);
    return new Filter[]{new HiddenHttpMethodFilter(), cef};
}
 
Example 13
/**
 * Initialize the filter.
 *
 * @throws ServletException when a servlet error occurs.
 */
public void initialize() throws ServletException {
    if (filter == null) {
        try {
            Class<? extends Filter> clazz = webApplication.getClassLoader().loadClass(className).asSubclass(Filter.class);
            filter = webApplication.createFilter(clazz);
        } catch (Throwable throwable) {
            throw new ServletException("Unable to initialize the filter", throwable);
        }
    }
}
 
Example 14
/**
 * 过滤器
 *
 * @param securityManager 权限管理器
 * @param shiroProperties shiro配置
 * @return 过滤器
 */
@Bean
@ConditionalOnMissingBean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager, ShiroProperties shiroProperties) {
    ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
    shiroFilterFactoryBean.setSecurityManager(securityManager);
    shiroFilterFactoryBean.setFilterChainDefinitionMap(shiroProperties.getFilterChainDefinitionMap());
    Map<String, Filter> filters = new LinkedHashMap<>();
    filters.put("jwt", new ShiroFilter());
    shiroFilterFactoryBean.setFilters(filters);
    return shiroFilterFactoryBean;
}
 
Example 15
Source Project: jump-the-queue   Source File: BaseWebSecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a simple filter that allows logout on a REST Url /services/rest/logout and returns a simple HTTP status 200
 * ok.
 *
 * @return the filter.
 */
protected Filter getSimpleRestLogoutFilter() {

  LogoutFilter logoutFilter = new LogoutFilter(new LogoutSuccessHandlerReturningOkHttpStatusCode(),
      new SecurityContextLogoutHandler());

  // configure logout for rest logouts
  logoutFilter.setLogoutRequestMatcher(new AntPathRequestMatcher("/services/rest/logout"));

  return logoutFilter;
}
 
Example 16
Source Project: java-technology-stack   Source File: PassThroughFilterChain.java    License: MIT License 5 votes vote down vote up
/**
 * Create a new PassThroughFilterChain that delegates to the given Filter,
 * calling it with the given FilterChain.
 * @param filter the Filter to delegate to
 * @param nextFilterChain the FilterChain to use for that next Filter
 */
public PassThroughFilterChain(Filter filter, FilterChain nextFilterChain) {
	Assert.notNull(filter, "Filter must not be null");
	Assert.notNull(nextFilterChain, "'FilterChain must not be null");
	this.filter = filter;
	this.nextFilterChain = nextFilterChain;
}
 
Example 17
Source Project: Tomcat7.0.67   Source File: InstanceEvent.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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)
 */
public InstanceEvent(Wrapper wrapper, Filter filter, String type) {

  super(wrapper);
  this.filter = filter;
  this.servlet = null;
  this.type = type;

}
 
Example 18
Source Project: data-highway   Source File: UserAgentMetricFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testName() throws Exception {
  when(request.getRequestURI()).thenReturn("/onramp/v1/roads/road1/messages");
  when(request.getHeader("User-Agent")).thenReturn("product1/1.0 product2/2.0 product3/3.0");
  Set<String> products = new HashSet<>(Arrays.asList("product1", "product2", "product4"));
  Filter underTest = new UserAgentMetricFilter(registry, products);

  underTest.doFilter(request, response, chain);

  assertThat(counter1.count(), is(1.0));
  assertThat(counter2.count(), is(1.0));
  assertThat(counter3.count(), is(0.0));
  assertThat(counter4.count(), is(0.0));
  verify(chain).doFilter(request, response);
}
 
Example 19
Source Project: seed   Source File: WebSecurityModule.java    License: Mozilla Public License 2.0 5 votes vote down vote up
private Key<? extends Filter> findKey(String filterName) {
    Key<? extends Filter> currentKey = null;
    if (DEFAULT_FILTERS.containsKey(filterName)) {
        currentKey = DEFAULT_FILTERS.get(filterName);
    } else {
        for (Class<? extends Filter> filterClass : customFilters) {
            String name = filterClass.getAnnotation(SecurityFilter.class).value();
            if (filterName.equals(name)) {
                currentKey = Key.get(filterClass);
            }
        }
    }
    return currentKey;
}
 
Example 20
Source Project: java-technology-stack   Source File: AbstractMockMvcBuilder.java    License: MIT License 5 votes vote down vote up
public final <T extends B> T addFilters(Filter... filters) {
	Assert.notNull(filters, "filters cannot be null");
	for (Filter f : filters) {
		Assert.notNull(f, "filters cannot contain null values");
		this.filters.add(f);
	}
	return self();
}
 
Example 21
Source Project: micro-server   Source File: FilterDataTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFilterData() {
	Filter filter = mock(Filter.class);
	FilterData data = new FilterData("mapping", "filterName", filter);
	assertThat(data.getMapping(), is("mapping"));
	assertThat(data.getFilterName(), is("filterName"));
	assertThat(data.getFilter(), is(filter));
}
 
Example 22
Source Project: spring-boot-shiro   Source File: ShiroAutoConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
private Map<String, Filter> instantiateFilterClasses(Map<String, Class<? extends Filter>> filters) {
    Map<String, Filter> filterMap = null;
    if (filters != null) {
        filterMap = new LinkedHashMap<String, Filter>();
        for (String name : filters.keySet()) {
            Class<? extends Filter> clazz = filters.get(name);
            Filter f = BeanUtils.instantiate(clazz);
            filterMap.put(name, f);
        }
    }
    return filterMap;
}
 
Example 23
Source Project: seed   Source File: WebSecurityModule.java    License: Mozilla Public License 2.0 5 votes vote down vote up
WebSecurityModule(ServletContext servletContext, WebSecurityConfig securityConfig,
        Collection<Class<? extends Filter>> customFilters, String applicationName,
        SecurityGuiceConfigurer securityGuiceConfigurer) {
    super(servletContext);
    this.securityConfig = securityConfig;
    this.customFilters = customFilters;
    this.applicationName = applicationName;
    this.securityGuiceConfigurer = securityGuiceConfigurer;
}
 
Example 24
Source Project: super-cloudops   Source File: IamFilterChainManager.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected NamedFilterList ensureChain(String chainName) {
	NamedFilterList chain = getChain(chainName);
	if (chain == null) {
		/*
		 * Cloning is required here, or multiple calls to the new
		 * SimpleNamedFilterList will result in additional premiseFilter
		 * duplication.
		 */
		chain = new SimpleNamedFilterList(chainName, (List<Filter>) premiseFilters.clone());
		getFilterChains().put(chainName, chain);
	}
	return chain;
}
 
Example 25
Source Project: utils   Source File: ShiroAutoConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
private Map<String, Filter> instantiateFilterClasses(Map<String, Class<? extends Filter>> filters) {
    Map<String, Filter> filterMap = null;
    if (filters != null) {
        filterMap = new LinkedHashMap<String, Filter>();
        for (String name : filters.keySet()) {
            Class<? extends Filter> clazz = filters.get(name);
            Filter f = BeanUtils.instantiate(clazz);
            filterMap.put(name, f);
        }
    }

    return filterMap;
}
 
Example 26
/**
 * sitemesh filter
 */
@Bean
public FilterRegistrationBean sitemesh() {
    FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
    registrationBean.setFilter(new SOSSiteMeshFilter());
    registrationBean.addUrlPatterns("/*");
    //注意: 在 spring security filter之后
    registrationBean.setOrder(8899);
    return registrationBean;
}
 
Example 27
@Test
public void noFilters() throws ServletException {
	initializer = new MyAnnotationConfigDispatcherServletInitializer() {
		@Override
		protected Filter[] getServletFilters() {
			return null;
		}
	};

	initializer.onStartup(servletContext);

	assertEquals(0, filterRegistrations.size());
}
 
Example 28
@Override
public Dynamic addFilter(String filterName, Filter filter) {
	if (filters.containsKey(filterName)) {
		return null;
	}
	filters.put(filterName, filter);
	MockFilterRegistration registration = new MockFilterRegistration();
	filterRegistrations.put(filterName, registration);
	return registration;
}
 
Example 29
Source Project: Tomcat7.0.67   Source File: InstanceSupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 exception Exception that occurred
 */
public void fireInstanceEvent(String type, Filter filter,
                              Throwable exception) {

    if (listeners.length == 0)
        return;

    InstanceEvent event = new InstanceEvent(wrapper, filter, type,
                                            exception);
    InstanceListener interested[] = listeners;
    for (int i = 0; i < interested.length; i++)
        interested[i].instanceEvent(event);

}
 
Example 30
Source Project: Tomcat7.0.67   Source File: InstanceEvent.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;

}