Java Code Examples for org.springframework.security.web.util.matcher.RequestMatcher

The following examples show how to use org.springframework.security.web.util.matcher.RequestMatcher. 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: youkefu   Source File: WebSecurityConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public Filter tokenInfoTokenFilterSecurityInterceptor() throws Exception
{
    RequestMatcher autconfig = new RegexRequestMatcher("/autoconfig([\\S\\s]*?)",null);
    RequestMatcher configprops = new RegexRequestMatcher("/configprops([\\S\\s]*?)",null);
    RequestMatcher beans = new RegexRequestMatcher("/beans([\\S\\s]*?)",null);
    RequestMatcher dump = new RegexRequestMatcher("/dump([\\S\\s]*?)",null);
    RequestMatcher env = new RegexRequestMatcher("/env([\\S\\s]*?)",null);
    RequestMatcher health = new RegexRequestMatcher("/health([\\S\\s]*?)",null);
    RequestMatcher info = new RegexRequestMatcher("/info([\\S\\s]*?)",null);
    RequestMatcher mappings = new RegexRequestMatcher("/mappings([\\S\\s]*?)",null);
    RequestMatcher metrics = new RegexRequestMatcher("/metrics([\\S\\s]*?)",null);
    RequestMatcher trace = new RegexRequestMatcher("/trace([\\S\\s]*?)",null);
    RequestMatcher druid = new RegexRequestMatcher("/druid([\\S\\s]*?)",null);
    
    RequestMatcher admin = new RegexRequestMatcher("/admin([\\S\\s]*?)",null);
    
    return new DelegateRequestMatchingFilter(autconfig , configprops , beans , dump , env , health , info , mappings , metrics , trace, druid , admin);
}
 
Example 2
Source Project: youkefu   Source File: DelegateRequestMatchingFilter.java    License: Apache License 2.0 6 votes vote down vote up
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
     HttpServletRequest request = (HttpServletRequest) req;
     boolean matchAnyRoles = false ;
     for(RequestMatcher anyRequest : ignoredRequests ){
    	 if(anyRequest.matches(request)){
    		 matchAnyRoles = true ;
    	 }
     }
     User user = (User) request.getSession().getAttribute(UKDataContext.USER_SESSION_NAME) ;
     if(matchAnyRoles){
    	 if(user !=null && "0".equals(user.getUsertype())){
    		 chain.doFilter(req,resp);
    	 }else{
     	 //重定向到 无权限执行操作的页面
     	 HttpServletResponse response = (HttpServletResponse) resp ;
     	 response.sendRedirect("/?msg=security");
    	 }
     }else{
    	 try{
    		 chain.doFilter(req,resp);
    	 }catch(ClientAbortException ex){
    		 //Tomcat异常,不做处理
    	 }
     }
}
 
Example 3
Source Project: FEBS-Cloud   Source File: ValidateCodeFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(@Nonnull HttpServletRequest httpServletRequest, @Nonnull HttpServletResponse httpServletResponse,
                                @Nonnull FilterChain filterChain) throws ServletException, IOException {
    String header = httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION);

    RequestMatcher matcher = new AntPathRequestMatcher(EndpointConstant.OAUTH_TOKEN, HttpMethod.POST.toString());
    if (matcher.matches(httpServletRequest)
            && StringUtils.equalsIgnoreCase(httpServletRequest.getParameter(ParamsConstant.GRANT_TYPE), GrantTypeConstant.PASSWORD)) {
        try {
            validateCode(httpServletRequest);
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } catch (Exception e) {
            FebsResponse febsResponse = new FebsResponse();
            FebsUtil.makeFailureResponse(httpServletResponse, febsResponse.message(e.getMessage()));
            log.error(e.getMessage(), e);
        }
    } else {
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
 
Example 4
Source Project: cosmo   Source File: SecurityFilterConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public FilterRegistrationBean<?> securityFilterChain() {
    FilterSecurityInterceptor securityFilter = new FilterSecurityInterceptor();
    securityFilter.setAuthenticationManager(this.authManager);
    securityFilter.setAccessDecisionManager(this.davDecisionManager);
    LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> metadata = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
    metadata.put(AnyRequestMatcher.INSTANCE, SecurityConfig.createList(ROLES));
    securityFilter.setSecurityMetadataSource(new DefaultFilterInvocationSecurityMetadataSource(metadata));

    /*
     * Note that the order in which filters are defined is highly important.
     */
    SecurityFilterChain filterChain = new DefaultSecurityFilterChain(AnyRequestMatcher.INSTANCE,
            this.cosmoExceptionFilter, this.extraTicketFilter, this.ticketFilter,
            new BasicAuthenticationFilter(authManager, this.authEntryPoint), securityFilter);
    FilterChainProxy proxy = new FilterChainProxy(filterChain);
    proxy.setFirewall(this.httpFirewall);
    FilterRegistrationBean<?> filterBean = new FilterRegistrationBean<>(proxy);
    filterBean.addUrlPatterns(PATH_DAV);
    return filterBean;
}
 
Example 5
/**
 * 更新权限集合
 */
public void setRequestMap(List<SysAuthorityVo> authorityVoList){
    Map<RequestMatcher, Collection<ConfigAttribute>> map = new ConcurrentHashMap<>();
    for (SysAuthorityVo sysAuthorityVo : authorityVoList) {
        String authorityName = sysAuthorityVo.getAuthorityName();
        if (StringUtils.isEmpty(sysAuthorityVo.getAuthorityContent())) continue;
        for (String url : sysAuthorityVo.getAuthorityContent().split(",")) {
            Collection<ConfigAttribute> value = map.get(new AntPathRequestMatcher(url));
            if (StringUtils.isEmpty(value)) {
                ArrayList<ConfigAttribute> configs = new ArrayList<>();
                configs.add(new SecurityConfig(authorityName));
                map.put(new AntPathRequestMatcher(url), configs);
            } else {
                value.add(new SecurityConfig(authorityName));
            }
        }
    }
    this.requestMap = map;
}
 
Example 6
Source Project: bearchoke   Source File: WebSecurityConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean(name = "authFilter")
public Filter authFilter() throws Exception {
    log.info("Creating authFilter...");

    RequestMatcher antReqMatch = new AntPathRequestMatcher(API_LOGIN_URL);

    List<RequestMatcher> reqMatches = new ArrayList<>();
    reqMatches.add(antReqMatch);
    RequestMatcher reqMatch = new AndRequestMatcher(reqMatches);

    UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
    filter.setPostOnly(true);
    filter.setUsernameParameter(USERNAME);
    filter.setPasswordParameter(PASSWORD);
    filter.setRequiresAuthenticationRequestMatcher(reqMatch);
    filter.setAuthenticationSuccessHandler(apiAuthenticationSuccessHandler);
    filter.setAuthenticationFailureHandler(apiAuthenticationFailureHandler);
    filter.setAuthenticationManager(authenticationManager());

    return filter;
}
 
Example 7
private void loadResourceDefine() {
   	// 在Web服务器启动时,提取系统中的所有权限。
	//应当是资源为key, 权限为value。 资源通常为url, 权限就是那些以ROLE_为前缀的角色。 一个资源可以由多个权限来访问。
	List<PermissionObject> query = aclService.findModulePermission();

	if(query != null && query.size() >0){
		for (PermissionObject permissionObject : query) {	
			String methods = null;
			if(permissionObject.getMethods() != null && !"".equals(permissionObject.getMethods())){
				methods = permissionObject.getMethods();
			}
			RequestMatcher matcher = new MyAntPathRequestMatcher(permissionObject.getUrl(), methods,true);
			Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();//权限
			ConfigAttribute ca = new SecurityConfig(permissionObject.getPermissionName()); 
			atts.add(ca);
			if(requestMap.get(matcher) != null){//处理附加URL情况	
				requestMap.get(matcher).add(ca);
			}else{
				requestMap.put(matcher,atts);
			}
		}
	}
}
 
Example 8
Source Project: lemon   Source File: UrlResourcePopulator.java    License: Apache License 2.0 6 votes vote down vote up
public void execute(FilterSecurityInterceptor filterSecurityInterceptor,
        Map<String, String> resourceMap) {
    Assert.notNull(filterSecurityInterceptor);
    Assert.notNull(resourceMap);

    logger.info("refresh url resource");

    LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = null;
    requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();

    for (Map.Entry<String, String> entry : resourceMap.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        requestMap.put(new AntPathRequestMatcher(key),
                SecurityConfig.createListFromCommaDelimitedString(value));
    }

    FilterInvocationSecurityMetadataSource source = new DefaultFilterInvocationSecurityMetadataSource(
            requestMap);
    filterSecurityInterceptor.setSecurityMetadataSource(source);
}
 
Example 9
/**
 * 所有资源列表
 * 一个页面的数组组装可能存在多个ajax,这里我使用逗号分隔的url字段来处理
 */
public Map<RequestMatcher, ConfigAttribute> resourceConfigAttributes() {

	Set<Resource> resources = this.findResourceByCondition();

	// 处理逗号分隔的url
	Set<Resource> extendSets = new HashSet<>();
	resources.forEach(resource -> {
		if (StringUtils.isNotEmpty(resource.getUrl()) && resource.getUrl().contains(",")){
			Arrays.asList(resource.getUrl().split(",")).forEach(urlSplit -> {
				try {
					Resource resourceClone = (Resource)resource.clone();
					resourceClone.setId(String.valueOf(idGenerate.nextId()));
					resourceClone.setUrl(urlSplit);
					extendSets.add(resourceClone);
				} catch (CloneNotSupportedException e) {
					LogBack.error(e.getMessage());
					e.printStackTrace();
				}

			});
		}
	});
	resources.removeIf(resource -> StringUtils.isNotEmpty(resource.getUrl()) && resource.getUrl().contains(","));
	resources.addAll(extendSets);

	Map<RequestMatcher, ConfigAttribute> map = resources.stream().collect(Collectors.toMap(
			resource -> {
				MvcRequestMatcher mvcRequestMatcher = new MvcRequestMatcher(mvcHandlerMappingIntrospector, resource.getUrl());
				mvcRequestMatcher.setMethod(HttpMethod.resolve(resource.getMethod()));
				return mvcRequestMatcher;
			},
			resource -> new SecurityConfig(resource.getCode())
			)
	);
	return map;
}
 
Example 10
Source Project: cerberus   Source File: WebSecurityConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
RequestMatcher getDoesRequestsRequireAuthMatcher() {

    List<RequestMatcher> whiteListMatchers =
        AUTHENTICATION_NOT_REQUIRED_WHITELIST.stream()
            .map(AntPathRequestMatcher::new)
            .collect(Collectors.toList());
    var whiteListMatcher = new OrRequestMatcher(whiteListMatchers);
    return request -> !whiteListMatcher.matches(request);
  }
 
Example 11
Source Project: onetwo   Source File: DatabaseSecurityMetadataSource.java    License: Apache License 2.0 5 votes vote down vote up
/****
 * 基于url匹配拦截时,转换为ExpressionBasedFilterInvocationSecurityMetadataSource
 * @param source
 * @return
 */
@Override
public void buildSecurityMetadataSource(){
	Assert.notNull(filterSecurityInterceptor, "filterSecurityInterceptor can not be null");
	this.buildRequestMap();
	
	Map<RequestMatcher, Collection<ConfigAttribute>> originRequestMap = getDefaultRequestMap();
	if(originRequestMap!=null && !originRequestMap.isEmpty()){
		this.requestMap.putAll(originRequestMap);
	}
	DefaultFilterInvocationSecurityMetadataSource fism = new DefaultFilterInvocationSecurityMetadataSource(requestMap);
	this.filterSecurityInterceptor.setSecurityMetadataSource(fism);
}
 
Example 12
Source Project: Milkomeda   Source File: CrustAuthenticationFilter.java    License: MIT License 5 votes vote down vote up
protected boolean permissiveRequest(HttpServletRequest request) {
    if (permissiveRequestMatchers == null)
        return false;
    for (RequestMatcher permissiveMatcher : permissiveRequestMatchers) {
        if (permissiveMatcher.matches(request))
            return true;
    }
    return false;
}
 
Example 13
Source Project: flowable-engine   Source File: ActuatorRequestMatcher.java    License: Apache License 2.0 5 votes vote down vote up
private RequestMatcher createDelegate(WebApplicationContext context) {
    try {
        String pathPrefix = getPathPrefix(context);
        RequestMatcherFactory requestMatcherFactory = new RequestMatcherFactory(pathPrefix);
        return createDelegate(context, requestMatcherFactory);
    } catch (NoSuchBeanDefinitionException ex) {
        return EMPTY_MATCHER;
    }
}
 
Example 14
@Autowired
public JwtTokenAuthenticationProcessingFilter(AuthenticationFailureHandler failureHandler,
                                              TokenExtractor tokenExtractor, RequestMatcher matcher) {
    super(matcher);
    this.failureHandler = failureHandler;
    this.tokenExtractor = tokenExtractor;
}
 
Example 15
Source Project: bdf3   Source File: UrlSecurityMetadataSource.java    License: Apache License 2.0 5 votes vote down vote up
public Collection<ConfigAttribute> getAttributes(Object object) {
	final HttpServletRequest request = ((FilterInvocation) object).getRequest();
	try {
		for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : getRequestMap()
			.entrySet()) {
			if (entry.getKey().matches(request)) {
				return entry.getValue();
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	
	return null;
}
 
Example 16
@Autowired
public JwtTokenAuthenticationProcessingFilter(AuthenticationFailureHandler failureHandler, 
        TokenExtractor tokenExtractor, RequestMatcher matcher) {
    super(matcher);
    this.failureHandler = failureHandler;
    this.tokenExtractor = tokenExtractor;
}
 
Example 17
Source Project: cola   Source File: CaptchaAuthenticationFilter.java    License: MIT License 5 votes vote down vote up
private AuthenticationFailureHandler requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
	for (RequestMatcher matcher : requestMatcherMap.keySet()) {
		if (matcher.matches(request)) {
			return requestMatcherMap.get(matcher);
		}
	}
	return null;
}
 
Example 18
/**
 * 在我们初始化的权限数据中找到对应当前url的权限数据
 */
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
    FilterInvocation fi = (FilterInvocation) object;
    HttpServletRequest request = fi.getRequest();

    //遍历我们初始化的权限数据,找到对应的url对应的权限
    for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : requestMap
            .entrySet()) {
        if (entry.getKey().matches(request)) {
            return entry.getValue();
        }
    }
    return null;
}
 
Example 19
Source Project: cerberus   Source File: AuditLoggingFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
  List<RequestMatcher> blackListMatchers =
      LOGGING_NOT_TRIGGERED_BLACKLIST.stream()
          .map(AntPathRequestMatcher::new)
          .collect(Collectors.toList());
  var blackListMatcher = new OrRequestMatcher(blackListMatchers);
  return blackListMatcher.matches(request);
}
 
Example 20
Source Project: fast-family-master   Source File: SecurityUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean skipPathRequest(HttpServletRequest request, String[] whiteList) {
    List<String> pathsToSkip = new ArrayList();
    pathsToSkip.addAll(Arrays.asList(whiteList));
    List<RequestMatcher> m = (List) pathsToSkip.stream().map((path) -> {
        return new AntPathRequestMatcher(path);
    }).collect(Collectors.toList());
    OrRequestMatcher matchers = new OrRequestMatcher(m);
    return matchers.matches(request);
}
 
Example 21
Source Project: incubator-atlas   Source File: AtlasSecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
public DelegatingAuthenticationEntryPoint getDelegatingAuthenticationEntryPoint() {
    LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPointMap = new LinkedHashMap<>();
    entryPointMap.put(new RequestHeaderRequestMatcher("User-Agent", "Mozilla"), atlasAuthenticationEntryPoint);
    DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(entryPointMap);
    entryPoint.setDefaultEntryPoint(getAuthenticationEntryPoint());
    return entryPoint;
}
 
Example 22
Source Project: onetwo   Source File: MutipleRequestMatcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
  public boolean matches(HttpServletRequest request) {
for(RequestMatcher matcher : matchers){
	if(matcher.matches(request)){
		return true;
	}
}
return false;
  }
 
Example 23
Source Project: ambari-logsearch   Source File: SecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
private LogsearchFilter logSearchConfigStateFilter() {
  RequestMatcher requestMatcher;
  if (logSearchConfigApiConfig.isSolrFilterStorage() || logSearchConfigApiConfig.isZkFilterStorage()) {
    requestMatcher = shipperConfigInputRequestMatcher();
  } else {
    requestMatcher = logsearchConfigRequestMatcher();
  }

  return new LogsearchFilter(requestMatcher, new ConfigStateProvider(logSearchConfigState, logSearchConfigApiConfig.isConfigApiEnabled()));
}
 
Example 24
Source Project: ambari-logsearch   Source File: LogsearchFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  requestMatcher = strictMock(RequestMatcher.class);
  statusProvider = strictMock(StatusProvider.class);
  servletRequest = strictMock(HttpServletRequest.class);
  servletResponse = strictMock(HttpServletResponse.class);
  filterChain = strictMock(FilterChain.class);

  expect(servletRequest.getRequestURI()).andReturn(REQUEST_URI).anyTimes();
}
 
Example 25
@Autowired
public JwtTokenAuthenticationProcessingFilter(AuthenticationFailureHandler failureHandler,
                                              TokenExtractor tokenExtractor, RequestMatcher matcher) {
    super(matcher);
    this.failureHandler = failureHandler;
    this.tokenExtractor = tokenExtractor;
}
 
Example 26
/**
     * 此方法是为了判定用户请求的url 是否在权限表中,如果在权限表中,则返回给 decide 方法。
     * object-->FilterInvocation
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

        FilterInvocation filterInvocation = (FilterInvocation) object;

        HttpServletRequest request = filterInvocation.getHttpRequest();

        if (resourceMap == null || resourceMap.size() == 0) {
            loadResource(request);
        }

        String requestUrl = filterInvocation.getRequestUrl();

        for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : resourceMap
            .entrySet()) {
            if (entry.getKey().matches(request)) {
                log.info("【" + requestUrl + "】匹配到DB权限列表");
                return entry.getValue();
            }
        }

        log.info("【" + requestUrl + "】不在DB权限列表当中,尝试匹配代码中的权限配置...");

///        return null; //默认白名单通过

        //  返回代码定义的默认配置(authenticated、permitAll等)
        Collection<ConfigAttribute> configAttributes = hardCodedSecurityMetadataSource.getAttributes(object);
        if (configAttributes == null || configAttributes.size() == 0) {
            log.info("【" + requestUrl + "】不在代码中的权限配置");
        } else {
            log.info("【" + requestUrl + "】匹配到代码中硬编码的配置或默认配置");
        }
        return configAttributes;
    }
 
Example 27
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
    Set<ConfigAttribute> allAttributes = new HashSet<>();

    for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : resourceMap
        .entrySet()) {
        allAttributes.addAll(entry.getValue());
    }

    return allAttributes;
}
 
Example 28
private boolean skipPathRequest(HttpServletRequest request, List<String> pathsToSkip ) {
  if(pathsToSkip == null)
    pathsToSkip = new ArrayList<String>();
  List<RequestMatcher> matchers = pathsToSkip.stream().map(path -> new AntPathRequestMatcher(path)).collect(Collectors.toList());
  OrRequestMatcher compositeMatchers = new OrRequestMatcher(matchers);
  return compositeMatchers.matches(request);
}
 
Example 29
Source Project: atlas   Source File: AtlasSecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
public DelegatingAuthenticationEntryPoint getDelegatingAuthenticationEntryPoint() throws Exception {
    LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPointMap = new LinkedHashMap<>();
    entryPointMap.put(new RequestHeaderRequestMatcher(HeadersUtil.USER_AGENT_KEY, HeadersUtil.USER_AGENT_VALUE), atlasAuthenticationEntryPoint);
    DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(entryPointMap);
    entryPoint.setDefaultEntryPoint(getAuthenticationEntryPoint());
    return entryPoint;
}
 
Example 30
Source Project: lemon   Source File: UrlSourceBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public void refresh() {
    if ((filterSecurityInterceptor == null) || (urlSourceFetcher == null)) {
        logger.info(
                "filterSecurityInterceptor : {}, urlSourceFetcher : {}",
                filterSecurityInterceptor, urlSourceFetcher);

        return;
    }

    logger.info("execute refresh");

    Map<String, String> resourceMap = urlSourceFetcher.getSource(null);

    LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = null;
    requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();

    for (Map.Entry<String, String> entry : resourceMap.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        requestMap.put(new AntPathRequestMatcher(key),
                SecurityConfig.createListFromCommaDelimitedString(value));
    }

    FilterInvocationSecurityMetadataSource source = new DefaultFilterInvocationSecurityMetadataSource(
            requestMap);
    filterSecurityInterceptor.setSecurityMetadataSource(source);
}