org.apache.shiro.web.filter.mgt.FilterChainManager Java Examples

The following examples show how to use org.apache.shiro.web.filter.mgt.FilterChainManager. 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: RestShiroFilterFactoryBean.java    From bootshiro with MIT License 6 votes vote down vote up
@Override
protected AbstractShiroFilter createInstance() throws Exception {
    LOGGER.debug("Creating Shiro Filter instance.");
    SecurityManager securityManager = this.getSecurityManager();
    String msg;
    if (securityManager == null) {
        msg = "SecurityManager property must be set.";
        throw new BeanInitializationException(msg);
    } else if (!(securityManager instanceof WebSecurityManager)) {
        msg = "The security manager does not implement the WebSecurityManager interface.";
        throw new BeanInitializationException(msg);
    } else {
        FilterChainManager manager = this.createFilterChainManager();
        RestPathMatchingFilterChainResolver chainResolver = new RestPathMatchingFilterChainResolver();
        chainResolver.setFilterChainManager(manager);
        return new RestShiroFilterFactoryBean.SpringShiroFilter((WebSecurityManager)securityManager, chainResolver);
    }
}
 
Example #2
Source File: OneFilterChainResolver.java    From onedev with MIT License 6 votes vote down vote up
@Inject
public OneFilterChainResolver(
		Set<FilterChainConfigurator> filterChainConfigurators, 
		BasicAuthenticationFilter basicAuthenticationFilter, 
		BearerAuthenticationFilter bearerAuthenticationFilter) {
	
	super();
	
	FilterChainManager filterChainManager = getFilterChainManager();
	
	filterChainManager.addFilter("authcBasic", basicAuthenticationFilter);
	filterChainManager.addFilter("authcBearer", bearerAuthenticationFilter);
	
	for (FilterChainConfigurator configurator: filterChainConfigurators)
		configurator.configure(filterChainManager);
	
	filterChainManager.createChain("/**", "authcBasic, authcBearer");
}
 
Example #3
Source File: CoreModule.java    From onedev with MIT License 6 votes vote down vote up
private void configureSecurity() {
	contributeFromPackage(Realm.class, AbstractAuthorizingRealm.class);
	
	bind(RememberMeManager.class).to(OneRememberMeManager.class);
	bind(WebSecurityManager.class).to(OneWebSecurityManager.class);
	bind(FilterChainResolver.class).to(OneFilterChainResolver.class);
	bind(BasicAuthenticationFilter.class);
	bind(BearerAuthenticationFilter.class);
	bind(PasswordService.class).to(OnePasswordService.class);
	bind(ShiroFilter.class);
	install(new ShiroAopModule());
       contribute(FilterChainConfigurator.class, new FilterChainConfigurator() {

           @Override
           public void configure(FilterChainManager filterChainManager) {
               filterChainManager.createChain("/**/info/refs", "noSessionCreation, authcBasic, authcBearer");
               filterChainManager.createChain("/**/git-upload-pack", "noSessionCreation, authcBasic, authcBearer");
               filterChainManager.createChain("/**/git-receive-pack", "noSessionCreation, authcBasic, authcBearer");
           }
           
       });
       contributeFromPackage(Authenticator.class, Authenticator.class);
}
 
Example #4
Source File: CoreModule.java    From onedev with MIT License 6 votes vote down vote up
private void configureRestServices() {
	bind(ResourceConfig.class).toProvider(ResourceConfigProvider.class).in(Singleton.class);
	bind(ServletContainer.class).to(DefaultServletContainer.class);
	
	contribute(FilterChainConfigurator.class, new FilterChainConfigurator() {

		@Override
		public void configure(FilterChainManager filterChainManager) {
			filterChainManager.createChain("/rest/**", "noSessionCreation, authcBasic");
		}
		
	});
	
	contribute(JerseyConfigurator.class, new JerseyConfigurator() {
		
		@Override
		public void configure(ResourceConfig resourceConfig) {
			resourceConfig.packages(RestConstants.class.getPackage().getName());
		}
		
	});
}
 
Example #5
Source File: MyShiroFilterFactoryBean.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
protected AbstractShiroFilter createInstance() throws Exception {
	SecurityManager securityManager = getSecurityManager();
	if (securityManager == null){
		throw new BeanInitializationException("SecurityManager property must be set.");
	}

	if (!(securityManager instanceof WebSecurityManager)){
		throw new BeanInitializationException("The security manager does not implement the WebSecurityManager interface.");
	}

	PathMatchingFilterChainResolver chainResolver = new PathMatchingFilterChainResolver();
	FilterChainManager chainManager = createFilterChainManager();
	chainResolver.setFilterChainManager(chainManager);
	return new MySpringShiroFilter((WebSecurityManager)securityManager, chainResolver);
}
 
Example #6
Source File: WebSecurityModule.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void configureShiroWeb() {
  bindRealm().to(EmptyRealm.class); // not used in practice, just here to keep Shiro module happy

  bindSingleton(SessionFactory.class, NexusSessionFactory.class);
  bindSingleton(SessionStorageEvaluator.class, NexusSessionStorageEvaluator.class);
  bindSingleton(SubjectDAO.class, NexusSubjectDAO.class);

  // configure our preferred security components
  bindSingleton(SessionDAO.class, NexusSessionDAO.class);
  bindSingleton(Authenticator.class, FirstSuccessfulModularRealmAuthenticator.class);
  bindSingleton(Authorizer.class, ExceptionCatchingModularRealmAuthorizer.class);
  bindSingleton(FilterChainManager.class, DynamicFilterChainManager.class);

  // path matching resolver has several constructors so we need to point Guice to the appropriate one
  bind(FilterChainResolver.class).toConstructor(ctor(PathMatchingFilterChainResolver.class)).asEagerSingleton();

  // bindings used by external modules
  expose(FilterChainResolver.class);
  expose(FilterChainManager.class);
}
 
Example #7
Source File: IamPathMatchingFilterChainResolver.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * Follow the Maximum Matching Principle <br/>
 * {@link org.springframework.web.servlet.handler.AbstractUrlHandlerMapping#lookupHandler}
 */
@Override
public FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain) {
	FilterChainManager chainManager = getFilterChainManager();
	state(chainManager.hasChains(), "Shiro filter chain must be implemented");

	// Current request URI
	String requestURI = getPathWithinApplication(request);

	// Candidate matching pattern list.
	List<String> candidateMatchingPatterns = new ArrayList<>(4);

	/*
	 * the 'chain names' in this implementation are actually path patterns
	 * defined by the user. We just use them as the chain name for the
	 * FilterChainManager's requirements
	 */
	for (String registeredPattern : chainManager.getChainNames()) {
		if (pathMatches(registeredPattern, requestURI)) {
			log.trace("Matched path pattern:[{}] for requestURI:[{}]. Utilizing corresponding filter chain...",
					registeredPattern, requestURI);
			candidateMatchingPatterns.add(registeredPattern);
		}
	}
	Collections.sort(candidateMatchingPatterns, new AntPatternComparator(requestURI));
	String bestMatch = candidateMatchingPatterns.get(0); // Best
	return chainManager.proxy(originalChain, bestMatch);
}
 
Example #8
Source File: RestPathMatchingFilterChainResolver.java    From Shiro-Action with MIT License 5 votes vote down vote up
@Override
public FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain) {
    FilterChainManager filterChainManager = getFilterChainManager();
    if (!filterChainManager.hasChains()) {
        return null;
    }

    String requestURI = getPathWithinApplication(request);

    // the 'chain names' in this implementation are actually path patterns defined by the user.  We just use them
    // as the chain name for the FilterChainManager's requirements
    for (String pathPattern : filterChainManager.getChainNames()) {

        String[] pathPatternArray = pathPattern.split("==");

        boolean httpMethodMatchFlag = true;

        if (pathPatternArray.length > 1) {
            httpMethodMatchFlag = pathPatternArray[1].equals(WebHelper.getRequestHTTPMethod());
        }

        // 只用过滤器链的 URL 部分与请求的 URL 进行匹配
        if (pathMatches(pathPatternArray[0], requestURI) && httpMethodMatchFlag) {
            if (log.isTraceEnabled()) {
                log.trace("Matched path pattern [" + pathPattern + "] for requestURI [" + requestURI + "].  " +
                        "Utilizing corresponding filter chain...");
            }
            return filterChainManager.proxy(originalChain, pathPattern);
        }
    }

    return null;
}
 
Example #9
Source File: RestPathMatchingFilterChainResolver.java    From bootshiro with MIT License 4 votes vote down vote up
/**
 * description TODO 重写filterChain匹配
 *
 * @param request 1
 * @param response 2
 * @param originalChain 3
 * @return javax.servlet.FilterChain
 */
@Override
public FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain) {
    FilterChainManager filterChainManager = this.getFilterChainManager();
    if (!filterChainManager.hasChains()) {
        return null;
    } else {
        String requestURI = this.getPathWithinApplication(request);
        if (requestURI != null && requestURI.endsWith(DEFAULT_PATH_SEPARATOR)) {
            requestURI = requestURI.substring(0, requestURI.length() - 1);
        }
        Iterator var6 = filterChainManager.getChainNames().iterator();

        String pathPattern;
        boolean flag = true;
        String[] strings = null;
        do {
            if (!var6.hasNext()) {
                return null;
            }

            pathPattern = (String)var6.next();

            strings = pathPattern.split("==");
            if (strings.length == NUM_2) {
                // 分割出url+httpMethod,判断httpMethod和request请求的method是否一致,不一致直接false
                if (WebUtils.toHttp(request).getMethod().toUpperCase().equals(strings[1].toUpperCase())) {
                    flag = false;
                } else {
                    flag = true;
                }
            } else {
                flag = false;
            }
            pathPattern = strings[0];
            if (pathPattern != null && pathPattern.endsWith(DEFAULT_PATH_SEPARATOR)) {
                pathPattern = pathPattern.substring(0, pathPattern.length() -1);
            }
        } while(!this.pathMatches(pathPattern, requestURI) || flag);

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Matched path pattern [" + pathPattern + "] for requestURI [" + requestURI + "].  Utilizing corresponding filter chain...");
        }
        if (strings.length == NUM_2) {
            pathPattern = pathPattern.concat("==").concat(WebUtils.toHttp(request).getMethod().toUpperCase());
        }

        return filterChainManager.proxy(originalChain, pathPattern);
    }
}
 
Example #10
Source File: AbstractIamConfiguration.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
@Bean
public FilterChainManager filterChainManager() {
	return new IamFilterChainManager();
}
 
Example #11
Source File: AbstractIamConfiguration.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
@Bean
public IamShiroFilterFactoryBean iamFilterFactoryBean(AbstractIamProperties<? extends ParamProperties> config,
		DefaultWebSecurityManager securityManager, FilterChainManager chainManager) {
	/*
	 * Note: The purpose of using Iam Shiro FilterFactory Bean is to use Iam
	 * Path Matching Filter Chain Resolver, while Iam Path Matching Filter
	 * Chain Resolver mainly implements the servlet/filter matching
	 * specification of getChain () method for default enhancements (because
	 * Shiro does not implement it, this causes serious problems)
	 */
	IamShiroFilterFactoryBean iamFilter = new IamShiroFilterFactoryBean(chainManager);
	iamFilter.setSecurityManager(securityManager);

	/*
	 * IAM server login page.(shiro default by "/login.jsp")
	 */
	iamFilter.setLoginUrl(config.getLoginUri());
	// Default login success callback URL.
	iamFilter.setSuccessUrl(config.getSuccessUri());
	// IAM server 403 page URL
	iamFilter.setUnauthorizedUrl(config.getUnauthorizedUri());

	// Register define filters.
	Map<String, Filter> filters = new LinkedHashMap<>();
	// Register define filter mapping.
	Map<String, String> filterChain = new LinkedHashMap<>();
	actx.getBeansWithAnnotation(IamFilter.class).values().stream().forEach(filter -> {
		String filterName = null, uriPertten = null;
		if (filter instanceof NameableFilter) {
			filterName = (String) invokeMethod(findMethod(filter.getClass(), "getName"), filter);
		}
		if (filter instanceof IamAuthenticationFilter) {
			uriPertten = ((IamAuthenticationFilter) filter).getUriMapping();
		}
		notNull(filterName, "'filterName' must not be null");
		notNull(uriPertten, "'uriPertten' must not be null");

		if (filters.putIfAbsent(filterName, (Filter) filter) != null) {
			throw new IllegalStateException(format("Already filter. [%s]", filterName));
		}
		if (filterChain.putIfAbsent(uriPertten, filterName) != null) {
			throw new IllegalStateException(format("Already filter mapping. [%s] = %s", uriPertten, filterName));
		}
	});
	// Filter chain definition register
	iamFilter.setFilters(filters);

	// Add external filter chain configuration
	config.getFilterChain().forEach((uriPertten, filterName) -> {
		if (filterChain.putIfAbsent(uriPertten, filterName) != null) {
			throw new IllegalStateException(format("Already filter mapping. [%s] = %s", uriPertten, filterName));
		}
	});

	// Filter chain mappings register
	iamFilter.setFilterChainDefinitionMap(filterChain);

	return iamFilter;
}
 
Example #12
Source File: IamShiroFilterFactoryBean.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
public IamShiroFilterFactoryBean(FilterChainManager chainManager) {
	Assert.notNull(chainManager, "chainManager is null, please check configure");
	this.chainManager = chainManager;
}
 
Example #13
Source File: FilterChainConfigurator.java    From onedev with MIT License votes vote down vote up
void configure(FilterChainManager filterChainManager);