org.springframework.util.PathMatcher.match()

Here are the examples of the java api org.springframework.util.PathMatcher.match() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

52 Examples 7

19 View Source File : DynamicSecurityMetadataSource.java
License : GNU General Public License v3.0
Project Creator : YuJian95

@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
    if (configAttributeMap == null) {
        this.loadDataSource();
    }
    List<ConfigAttribute> configAttributes = new ArrayList<>();
    // 获取当前访问的路径
    String url = ((FilterInvocation) o).getRequestUrl();
    String path = URLUtil.getPath(url);
    PathMatcher pathMatcher = new AntPathMatcher();
    Iterator<String> iterator = configAttributeMap.keySet().iterator();
    // 获取访问该路径所需资源
    while (iterator.hasNext()) {
        String pattern = iterator.next();
        if (pathMatcher.match(pattern, path)) {
            configAttributes.add(configAttributeMap.get(pattern));
        }
    }
    // 未设置操作请求权限,返回空集合
    return configAttributes;
}

19 View Source File : MappedInterceptor.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Determine a match for the given lookup path.
 * @param lookupPath the current request path
 * @param pathMatcher a path matcher for path pattern matching
 * @return {@code true} if the interceptor applies to the given request path
 */
public boolean matches(String lookupPath, PathMatcher pathMatcher) {
    PathMatcher pathMatcherToUse = (this.pathMatcher != null ? this.pathMatcher : pathMatcher);
    if (!ObjectUtils.isEmpty(this.excludePatterns)) {
        for (String pattern : this.excludePatterns) {
            if (pathMatcherToUse.match(pattern, lookupPath)) {
                return false;
            }
        }
    }
    if (ObjectUtils.isEmpty(this.includePatterns)) {
        return true;
    }
    for (String pattern : this.includePatterns) {
        if (pathMatcherToUse.match(pattern, lookupPath)) {
            return true;
        }
    }
    return false;
}

19 View Source File : DynamicSecurityMetadataSource.java
License : MIT License
Project Creator : tongji4m3

@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
    if (configAttributeMap == null)
        this.loadDataSource();
    List<ConfigAttribute> configAttributes = new ArrayList<>();
    // 获取当前访问的路径
    String url = ((FilterInvocation) o).getRequestUrl();
    String path = URLUtil.getPath(url);
    PathMatcher pathMatcher = new AntPathMatcher();
    Iterator<String> iterator = configAttributeMap.keySet().iterator();
    // 获取访问该路径所需资源
    while (iterator.hasNext()) {
        String pattern = iterator.next();
        if (pathMatcher.match(pattern, path)) {
            configAttributes.add(configAttributeMap.get(pattern));
        }
    }
    // 未设置操作请求权限,返回空集合
    return configAttributes;
}

19 View Source File : DynamicSecurityMetadataSource.java
License : MIT License
Project Creator : tongji4m3

@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
    if (configAttributeMap == null)
        this.loadDataSource();
    List<ConfigAttribute> configAttributes = new ArrayList<>();
    String url = ((FilterInvocation) o).getRequestUrl();
    String path = URLUtil.getPath(url);
    PathMatcher pathMatcher = new AntPathMatcher();
    Iterator<String> iterator = configAttributeMap.keySet().iterator();
    while (iterator.hasNext()) {
        String pattern = iterator.next();
        if (pathMatcher.match(pattern, path)) {
            configAttributes.add(configAttributeMap.get(pattern));
        }
    }
    return configAttributes;
}

19 View Source File : PathMatcherServerWebExchangeMatcherTests.java
License : Apache License 2.0
Project Creator : spring-projects

@Test
public void matchesWhenPathMatcherTrueAndMethodTrueThenReturnTrue() {
    matcher = new PathMatcherServerWebExchangeMatcher(pattern, exchange.getRequest().getMethod());
    matcher.setPathMatcher(pathMatcher);
    when(pathMatcher.match(pattern, path)).thenReturn(true);
    replacedertThat(matcher.matches(exchange).isMatch()).isTrue();
}

19 View Source File : PathMatcherServerWebExchangeMatcherTests.java
License : Apache License 2.0
Project Creator : spring-projects

@Test
public void matchesWhenPathMatcherTrueThenReturnTrue() {
    when(pathMatcher.match(pattern, path)).thenReturn(true);
    replacedertThat(matcher.matches(exchange).isMatch()).isTrue();
}

19 View Source File : PathMatcherServerWebExchangeMatcherTests.java
License : Apache License 2.0
Project Creator : spring-projects

@Test
public void matchesWhenPathMatcherFalseThenReturnFalse() {
    when(pathMatcher.match(pattern, path)).thenReturn(false);
    replacedertThat(matcher.matches(exchange).isMatch()).isFalse();
    verify(pathMatcher).match(pattern, path);
}

19 View Source File : PathFilter.java
License : Apache License 2.0
Project Creator : spring-io

private boolean hasMatch(PathMatcher pathMatcher, String path, List<String> patterns) {
    for (String pattern : patterns) {
        pattern = cleanPattern(path, pattern);
        if (pathMatcher.match(pattern, path)) {
            return true;
        }
    }
    return false;
}

19 View Source File : MappedInterceptor.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Returns {@code true} if the interceptor applies to the given request path.
 * @param lookupPath the current request path
 * @param pathMatcher a path matcher for path pattern matching
 */
public boolean matches(String lookupPath, PathMatcher pathMatcher) {
    PathMatcher pathMatcherToUse = (this.pathMatcher != null) ? this.pathMatcher : pathMatcher;
    if (this.excludePatterns != null) {
        for (String pattern : this.excludePatterns) {
            if (pathMatcherToUse.match(pattern, lookupPath)) {
                return false;
            }
        }
    }
    if (this.includePatterns == null) {
        return true;
    } else {
        for (String pattern : this.includePatterns) {
            if (pathMatcherToUse.match(pattern, lookupPath)) {
                return true;
            }
        }
        return false;
    }
}

19 View Source File : RegexUtil.java
License : Apache License 2.0
Project Creator : kplxq

/**
 * ant风格URL是否匹配
 * @param pattern
 * @param url
 * @return
 */
public static boolean antUrlMatch(String antPattern, String url) {
    return antPathMatcher.match(antPattern, url);
}

19 View Source File : TalosServletFilter.java
License : Apache License 2.0
Project Creator : kplxq

private boolean isNeedFilter(String[] patternArray, String url) {
    for (String whiteURL : patternArray) {
        if (pathMatcher.match(whiteURL, url)) {
            return true;
        }
    }
    return false;
}

19 View Source File : N2oRouter.java
License : Apache License 2.0
Project Creator : i-novus-llc

/**
 * Сопоставляет URL в RouteInfo с url в параметре
 *
 * @param info        Информация об URL адресе
 * @param urlMatching URL шаблон в Ant стиле
 * @return Сопоставимы или нет
 */
private boolean matchInfo(RouteInfoKey info, String urlMatching) {
    return pathMatcher.match(info.getUrlMatching(), urlMatching);
}

19 View Source File : PathMatchingHandlerChainResolver.java
License : Apache License 2.0
Project Creator : hiwepy

protected boolean pathMatches(String pattern, String path) {
    PathMatcher pathMatcher = getPathMatcher();
    return pathMatcher.match(pattern, path);
}

19 View Source File : AbstractPathMatchMessageHandler.java
License : Apache License 2.0
Project Creator : hiwepy

protected boolean pathsMatch(String pattern, String path) {
    return pathMatcher.match(pattern, path);
}

19 View Source File : Matcher.java
License : Apache License 2.0
Project Creator : Frodez

/**
 * 判断是否为免验证路径<br>
 * 路径获取方式:<br>
 * <code>
 * HttpServletRequest request = ...;
 * String uri = request.getRequestURI();
 * </code><br>
 * <strong>true为需要验证,false为不需要验证</strong><br>
 * @author Frodez
 * @date 2019-03-10
 */
public static boolean isPermitAllPath(String uri) {
    // 对于存在的路径,这里就可以直接判断
    if (permitPaths.contains(uri)) {
        return true;
    }
    // 对于可能出现的错误路径,交由matcher判断
    for (String path : basePermitPaths) {
        if (matcher.match(path, uri)) {
            return true;
        }
    }
    return false;
}

19 View Source File : AntRoutePathMatcher.java
License : Apache License 2.0
Project Creator : eacdy

@Override
public boolean test(ServerWebExchange exchange) {
    String path = exchange.getRequest().getPath().value();
    if (canMatch) {
        return pathMatcher.match(pattern, path);
    }
    return false;
}

19 View Source File : HttpRequestUtils.java
License : Apache License 2.0
Project Creator : baidao

public static boolean isInclude(String uri, String... includes) {
    boolean isInclude = false;
    if (includes != null) {
        for (String resource : includes) {
            if (pathMatcher.match(resource, uri)) {
                isInclude = true;
                break;
            }
        }
    }
    return isInclude;
}

19 View Source File : PrefixRoutePathMatcher.java
License : Apache License 2.0
Project Creator : alibaba

@Override
public boolean test(HttpRequestMessage context) {
    String path = context.getPath();
    if (canMatch) {
        return pathMatcher.match(pattern, path);
    }
    return false;
}

18 View Source File : SysBaseApiImpl.java
License : Apache License 2.0
Project Creator : zhangdaiscott

/**
 *  匹配前端传过来的地址 匹配成功返回正则地址
 *  AntPathMatcher匹配地址
 * ()* 匹配0个或多个字符
 * ()**匹配0个或多个目录
 */
private String getRegexpUrl(String url) {
    List<String> list = sysPermissionMapper.queryPermissionUrlWithStar();
    if (list != null && list.size() > 0) {
        for (String p : list) {
            PathMatcher matcher = new AntPathMatcher();
            if (matcher.match(p, url)) {
                return p;
            }
        }
    }
    return null;
}

18 View Source File : JWTAuthenticationTokenFilter.java
License : Apache License 2.0
Project Creator : u014427391

private Boolean checkRequestUri(String requestUri) {
    boolean filter = true;
    final PathMatcher pathMatcher = new AntPathMatcher();
    for (String permitUri : permitAllUris) {
        if (pathMatcher.match(permitUri, requestUri)) {
            // permit all的链接直接放过
            filter = true;
        }
    }
    for (String authUri : authenticateUris) {
        if (pathMatcher.match(authUri, requestUri)) {
            filter = false;
        }
    }
    return filter;
}

18 View Source File : TracingFilter.java
License : Apache License 2.0
Project Creator : TFdream

private boolean isExcludedUri(String uri) {
    if (StringUtils.isEmpty(uri)) {
        return false;
    }
    if (CollectionUtils.isEmpty(excludedUris)) {
        return false;
    }
    for (String ex : excludedUris) {
        if (pathMatcher.match(ex, uri))
            return true;
    }
    return false;
}

18 View Source File : DefaultBusPathMatcher.java
License : Apache License 2.0
Project Creator : osswangxining

protected boolean matchMultiProfile(String pattern, String applicationContextID) {
    log.debug("matchMultiProfile : " + pattern + ", " + applicationContextID);
    // parse the application-context-id
    String[] appContextIDTokens = tokenizeToStringArray(applicationContextID, ":");
    if (appContextIDTokens.length <= 1) {
        // no parts, default to delegate which already returned false;
        return false;
    }
    String selfProfiles = appContextIDTokens[1];
    // short circuit if possible
    String[] profiles = tokenizeToStringArray(selfProfiles, ",");
    if (profiles.length == 1) {
        // there aren't multiple profiles to check, the delegate match was
        // originally false so return what delegate determined
        return false;
    }
    // gather candidate ids with a single profile rather than a comma separated list
    String[] idsWithSingleProfile = new String[profiles.length];
    for (int i = 0; i < profiles.length; i++) {
        // replace comma separated profiles with single profile
        String profile = profiles[i];
        String[] newTokens = new String[appContextIDTokens.length];
        System.arraycopy(appContextIDTokens, 0, newTokens, 0, appContextIDTokens.length);
        newTokens[1] = profile;
        idsWithSingleProfile[i] = StringUtils.arrayToDelimitedString(newTokens, ":");
    }
    for (String id : idsWithSingleProfile) {
        if (delagateMatcher.match(pattern, id)) {
            log.debug("matched true");
            return true;
        }
    }
    log.debug("matched false");
    return false;
}

18 View Source File : PathMatchInterceptorAdapter.java
License : MIT License
Project Creator : liuxx-u

protected boolean match(HttpServletRequest request, String[] uriPatterns) {
    String uri = request.getRequestURI();
    PathMatcher pathMatcher = getPathMatcher();
    for (String uriPattern : uriPatterns) {
        if (pathMatcher.match(uriPattern, uri)) {
            return true;
        }
    }
    return false;
}

18 View Source File : PathMatchInterceptorAdapter.java
License : MIT License
Project Creator : liuxx-u

protected boolean match(HttpServletRequest request, String uriPattern) {
    PathMatcher pathMatcher = getPathMatcher();
    return pathMatcher.match(uriPattern, request.getRequestURI());
}

18 View Source File : AntPathFilter.java
License : GNU Lesser General Public License v3.0
Project Creator : lets-mica

@Override
public boolean accept(File pathname) {
    String filePath = pathname.getAbsolutePath();
    return PATH_MATCHER.match(pattern, filePath);
}

18 View Source File : JwtAuthenticationFilter.java
License : Apache License 2.0
Project Creator : jitwxs

/**
 * 忽略目录
 * @author jitwxs
 * @since 2018/6/28 9:32
 */
private boolean disProtectedUrl(HttpServletRequest request) {
    if (pathMatcher.match("/doc.html", request.getServletPath())) {
        return true;
    }
    if (pathMatcher.match("/auth/**", request.getServletPath())) {
        return true;
    }
    if (pathMatcher.match("/ws/**", request.getServletPath())) {
        return true;
    }
    return false;
}

18 View Source File : DynamicSecurityMetadataSource.java
License : Apache License 2.0
Project Creator : haoyu21

@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
    if (configAttributeMap == null) {
        this.loadDataSource();
    }
    List<ConfigAttribute> configAttributes = new ArrayList<>();
    // 获取当前访问的路径
    String url = ((FilterInvocation) o).getRequestUrl();
    String path = URLUtil.getPath(url);
    PathMatcher pathMatcher = new AntPathMatcher();
    // 获取访问该路径所需资源
    for (String pattern : configAttributeMap.keySet()) {
        if (pathMatcher.match(pattern, path)) {
            configAttributes.add(configAttributeMap.get(pattern));
        }
    }
    // 未设置操作请求权限,返回空集合
    return configAttributes;
}

18 View Source File : URIMatcher.java
License : Apache License 2.0
Project Creator : ainilili

@Override
public boolean match(Caller caller, String pattern) {
    HttpServletRequest request = caller.getRequest();
    String location = request.getMethod() + " " + request.getRequestURI();
    if (pattern.startsWith("/")) {
        pattern = "* " + pattern;
    }
    return antMatcher.match(pattern, location);
}

18 View Source File : WebTokenHandlerInterceptor.java
License : MIT License
Project Creator : 7upcat

private boolean isIgnoreUri(String uri) {
    if (null == ignoreUriPatterns)
        return false;
    return Arrays.asList(ignoreUriPatterns).stream().anyMatch(p -> pathMatcher.match(p, uri));
}

17 View Source File : XssFilter.java
License : MIT License
Project Creator : YunaiV

@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
    // 如果关闭,则不过滤
    if (!properties.isEnable()) {
        return true;
    }
    // 如果匹配到无需过滤,则不过滤
    String uri = request.getRequestURI();
    return properties.getExcludeUrls().stream().anyMatch(excludeUrl -> pathMatcher.match(excludeUrl, uri));
}

17 View Source File : RequestCorrelationInspectorFilter.java
License : Apache License 2.0
Project Creator : telstra

@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
    return EXCLUDE_PATTERNS.stream().anyMatch(p -> matcher.match(p, request.getServletPath()));
}

17 View Source File : JwtAuthenticationFilter.java
License : Apache License 2.0
Project Creator : jitwxs

// 只对/api/*下请求拦截
private boolean isProtectedUrl(HttpServletRequest request) {
    return pathMatcher.match("/api/**", request.getServletPath());
}

17 View Source File : DefaultMessagingManager.java
License : Apache License 2.0
Project Creator : jetlinks

@Override
public Flux<Message> subscribe(SubscribeRequest request) {
    return Flux.defer(() -> {
        for (Map.Entry<String, SubscriptionProvider> entry : subProvider.entrySet()) {
            if (matcher.match(entry.getKey(), request.getTopic())) {
                return entry.getValue().subscribe(request).map(v -> {
                    if (v instanceof Message) {
                        return ((Message) v);
                    }
                    return Message.success(request.getId(), request.getTopic(), v);
                });
            }
        }
        return Flux.error(new UnsupportedOperationException("不支持的topic"));
    });
}

17 View Source File : SwaggerConfiguration.java
License : GNU General Public License v3.0
Project Creator : halo-dev

private List<SecurityContext> adminSecurityContext() {
    final PathMatcher pathMatcher = new AntPathMatcher();
    return Collections.singletonList(SecurityContext.builder().securityReferences(adminApiAuths()).operationSelector(operationContext -> {
        var requestMappingPattern = operationContext.requestMappingPattern();
        return pathMatcher.match("/api/admin/**/*", requestMappingPattern);
    }).build());
}

17 View Source File : SwaggerConfiguration.java
License : GNU General Public License v3.0
Project Creator : halo-dev

private List<SecurityContext> contentSecurityContext() {
    final PathMatcher pathMatcher = new AntPathMatcher();
    return Collections.singletonList(SecurityContext.builder().securityReferences(contentApiAuths()).operationSelector(operationContext -> {
        var requestMappingPattern = operationContext.requestMappingPattern();
        return pathMatcher.match("/api/content/**/*", requestMappingPattern);
    }).build());
}

17 View Source File : PrefixRoutePathMatcher.java
License : Apache License 2.0
Project Creator : eacdy

@Override
public boolean test(RequestContext context) {
    String path = context.getRequest().getServletPath();
    if (canMatch) {
        return pathMatcher.match(pattern, path);
    }
    return false;
}

17 View Source File : AuthenticFilter.java
License : Apache License 2.0
Project Creator : biezhi

/**
 * Determine a match for the given lookup path.
 *
 * @param lookupPath  the current request path
 * @param pathMatcher a path matcher for path pattern matching
 * @return {@code true} if the interceptor applies to the given request path
 */
protected boolean matches(String lookupPath, PathMatcher pathMatcher) {
    PathMatcher pathMatcherToUse = (this.pathMatcher != null ? this.pathMatcher : pathMatcher);
    if (!ObjectUtils.isEmpty(this.excludePatterns)) {
        for (String pattern : this.excludePatterns) {
            if (pathMatcherToUse.match(pattern, lookupPath)) {
                return false;
            }
        }
    }
    if (ObjectUtils.isEmpty(this.includePatterns)) {
        return true;
    }
    for (String pattern : this.includePatterns) {
        if (pathMatcherToUse.match(pattern, lookupPath)) {
            return true;
        }
    }
    return false;
}

16 View Source File : UrlPatternManager.java
License : MIT License
Project Creator : yangziwen

public static String getBestMatchedUrlPattern(String url) {
    if (StringUtils.isEmpty(url)) {
        return PATTERN_UNKNOWN;
    }
    int paramStartIdx = url.indexOf("?");
    String path = paramStartIdx >= 0 ? url.substring(0, paramStartIdx) : url;
    if (StringUtils.isEmpty(path)) {
        return PATTERN_UNKNOWN;
    }
    if (simpleUrlPatterns.contains(path)) {
        return path;
    }
    String[] array = StringUtils.split(path, "/");
    if (ArrayUtils.isEmpty(array)) {
        return PATTERN_UNKNOWN;
    }
    String prefix = array[0];
    Collection<String> urlPatterns = Collections.emptySet();
    if (prefixKeyedUrlMap.containsKey(prefix)) {
        urlPatterns = prefixKeyedUrlMap.get(prefix);
    } else {
        urlPatterns = complicatedUrlPatterns;
    }
    return urlPatterns.stream().filter(pattern -> URL_PATH_MATCHER.match(pattern, path)).sorted(URL_PATH_MATCHER.getPatternComparator(path)).findFirst().orElse(PATTERN_UNKNOWN);
}

16 View Source File : PermissionDataAspect.java
License : MIT License
Project Creator : smallyunet

/**
 *  匹配前端传过来的地址 匹配成功返回正则地址
 *  AntPathMatcher匹配地址
 * ()* 匹配0个或多个字符
 * ()**匹配0个或多个目录
 */
private String getRegexpUrl(String url) {
    List<String> list = sysPermissionService.queryPermissionUrlWithStar();
    if (list != null && list.size() > 0) {
        for (String p : list) {
            PathMatcher matcher = new AntPathMatcher();
            if (matcher.match(p, url)) {
                return p;
            }
        }
    }
    return null;
}

16 View Source File : MyAntPathRequestMatcher.java
License : GNU Affero General Public License v3.0
Project Creator : diyhi

/**
 * Returns true if the configured pattern (and HTTP-Method) match those of the supplied request.
 * 修改
 * @param request the request to match against. The ant pattern will be matched against the
 *    {@code servletPath} + {@code pathInfo} of the request.
 */
public boolean matches(HttpServletRequest request) {
    if (httpMethod != null && request.getMethod() != null && httpMethod != HttpMethod.valueOf(request.getMethod())) {
        if (logger.isDebugEnabled()) {
            logger.debug("Request '" + request.getMethod() + " " + getRequestPath(request) + "'" + " doesn't match '" + httpMethod + " " + pattern);
        }
        return false;
    }
    if (pattern.equals(MATCH_ALL)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Request '" + getRequestPath(request) + "' matched by universal pattern '/**'");
        }
        return true;
    }
    // 删除URL的路径和虚拟目录
    String url = UrlUtils.buildRequestUrl(request);
    return pathMatcher.match(pattern, url);
}

16 View Source File : GatewayJwtWebFilter.java
License : Apache License 2.0
Project Creator : dibo-software

/**
 * WebFilter实现,移除匿名url的认证header头等
 * @param exchange
 * @param chain
 * @return
 */
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    // 移除匿名URL的auth头
    List<String> anonUrls = configProperties.getAnonUrls();
    if (V.notEmpty(anonUrls)) {
        for (String anonUrl : anonUrls) {
            if (PATH_MATCHER.match(anonUrl, request.getURI().getPath())) {
                request = exchange.getRequest().mutate().header(Cons.JWT_TOKEN_HEADER_NAME, "").build();
                exchange = exchange.mutate().request(request).build();
                return chain.filter(exchange);
            }
        }
    }
    return chain.filter(exchange);
}

16 View Source File : PrefixRoutePathMatcher.java
License : Apache License 2.0
Project Creator : alibaba

@Override
public boolean test(RequestContext context) {
    // Solve the problem of prefix matching
    HttpServletRequest request = context.getRequest();
    String path = request.getRequestURI();
    if (path == null) {
        replacedertUtil.replacedertNotBlank(pattern, "requesturi cannot be blank");
    }
    if (canMatch) {
        return pathMatcher.match(pattern, path);
    }
    return false;
}

15 View Source File : GatewayAuthorizationManager.java
License : Apache License 2.0
Project Creator : dibo-software

@Override
public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
    // 开发模式下,忽略权限检查
    if (isDevelopmentMode()) {
        log.info("开发模式已启用,权限检查将被忽略!");
        return Mono.just(new AuthorizationDecision(true));
    }
    // 从Redis中获取当前路径可访问角色列表
    ServerHttpRequest request = authorizationContext.getExchange().getRequest();
    Map<Object, Object> resourceRolesMap = redisTemplate.opsForHash().entries(RedisCons.KEY_RESOURCE_ROLES_MAP);
    // 请求URI
    String requestUri = request.getMethodValue().toUpperCase() + ":" + request.getURI().getPath();
    // 先匹配固定URI
    List<String> matchRoles = null;
    if (resourceRolesMap.containsKey(requestUri)) {
        matchRoles = (List<String>) resourceRolesMap.get(requestUri);
    } else {
        // 前缀
        for (Map.Entry<Object, Object> entry : resourceRolesMap.entrySet()) {
            if (PATH_MATCHER.match((String) entry.getKey(), requestUri)) {
                matchRoles = (List<String>) entry.getValue();
                break;
            }
        }
    }
    // 无须检查权限的url,忽略
    if (matchRoles == null) {
        log.debug("忽略无权限约束的URL: {}", requestUri);
        return Mono.just(new AuthorizationDecision(true));
    }
    log.debug("检查权限:URL: {}, 可访问Roles: {}", requestUri, matchRoles);
    // 当前URL允许角色范围内的用户可访问
    return mono.filter(Authentication::isAuthenticated).flatMapIterable(Authentication::getAuthorities).map(GrantedAuthority::getAuthority).any(matchRoles::contains).map(AuthorizationDecision::new).defaultIfEmpty(new AuthorizationDecision(false));
}

13 View Source File : SecureResourceFilterInvocationDefinitionSource.java
License : MIT License
Project Creator : keets2012

@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
    logger.info("getAttributes");
    // 应该做instanceof
    FilterInvocation filterInvocation = (FilterInvocation) o;
    // String method = filterInvocation.getHttpRequest().getMethod();
    String requestURI = filterInvocation.getRequestUrl();
    // 循环资源路径,当访问的Url和资源路径url匹配时,返回该Url所需要的权限
    for (Iterator<Map.Entry<String, Collection<ConfigAttribute>>> iter = map.entrySet().iterator(); iter.hasNext(); ) {
        Map.Entry<String, Collection<ConfigAttribute>> entry = iter.next();
        String url = entry.getKey();
        if (matcher.match(url, requestURI)) {
            return map.get(requestURI);
        }
    }
    return null;
}

12 View Source File : DynamicSecurityFilter.java
License : MIT License
Project Creator : tongji4m3

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain);
    if (request.getMethod().equals(HttpMethod.OPTIONS.toString())) {
        fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
        return;
    }
    PathMatcher pathMatcher = new AntPathMatcher();
    for (String path : ignoreUrlsConfig.getUrls()) {
        if (pathMatcher.match(path, request.getRequestURI())) {
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
            return;
        }
    }
    InterceptorStatusToken token = super.beforeInvocation(fi);
    try {
        fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
    } finally {
        super.afterInvocation(token, null);
    }
}

12 View Source File : IgnoreUrlsRemoveJwtFilter.java
License : Apache License 2.0
Project Creator : macrozheng

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    URI uri = request.getURI();
    PathMatcher pathMatcher = new AntPathMatcher();
    // 白名单路径移除JWT请求头
    List<String> ignoreUrls = ignoreUrlsConfig.getUrls();
    for (String ignoreUrl : ignoreUrls) {
        if (pathMatcher.match(ignoreUrl, uri.getPath())) {
            request = exchange.getRequest().mutate().header(AuthConstant.JWT_TOKEN_HEADER, "").build();
            exchange = exchange.mutate().request(request).build();
            return chain.filter(exchange);
        }
    }
    return chain.filter(exchange);
}

11 View Source File : DynamicSecurityFilter.java
License : GNU General Public License v3.0
Project Creator : YuJian95

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain);
    // OPTIONS请求直接放行
    if (request.getMethod().equals(HttpMethod.OPTIONS.toString())) {
        fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
        return;
    }
    // 白名单请求直接放行
    PathMatcher pathMatcher = new AntPathMatcher();
    for (String path : ignoreUrlsConfig.getUrls()) {
        if (pathMatcher.match(path, request.getRequestURI())) {
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
            return;
        }
    }
    // 此处会调用AccessDecisionManager中的decide方法进行鉴权操作
    InterceptorStatusToken token = super.beforeInvocation(fi);
    try {
        fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
    } finally {
        super.afterInvocation(token, null);
    }
}

11 View Source File : AuthGlobalFilter.java
License : Apache License 2.0
Project Creator : mtcarpenter

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    // 防止 OPTIONS 请求直接放行
    if (request.getMethod().equals(HttpMethod.OPTIONS)) {
        return chain.filter(exchange);
    }
    // 白名单请求直接放行
    PathMatcher pathMatcher = new AntPathMatcher();
    for (String path : ignoreUrlsConfig.getUrls()) {
        if (pathMatcher.match("/**" + path, request.getPath().toString())) {
            return chain.filter(exchange);
        }
    }
    // token 验证
    String token = request.getHeaders().getFirst(tokenHeader);
    if (StringUtils.isBlank(token)) {
        log.error("token = {}", token);
        throw new ApiException(ResultCode.UNAUTHORIZED);
    }
    String username = jwtTokenUtil.getUserNameFromToken(token);
    // 待抽离
    String key = REDIS_DATABASE + ":" + REDIS_KEY_TOKEN + ":" + username;
    String resultToken = stringRedisTemplate.opsForValue().get(key);
    if (StringUtils.isBlank(resultToken)) {
        log.error("resultToken = {}", resultToken);
        throw new ApiException(ResultCode.UNAUTHORIZED);
    }
    log.error("resultToken = {}", resultToken);
    return chain.filter(exchange);
}

11 View Source File : Matcher.java
License : Apache License 2.0
Project Creator : Frodez

@PostConstruct
private void init() {
    SecurityProperties securityProperties = ContextUtil.bean(SecurityProperties.clreplaced);
    matcher = ContextUtil.bean(PathMatcher.clreplaced);
    String basePath = PropertyUtil.get(PropertyKey.Web.BASE_PATH);
    // 预处理所有允许的路径,这里的路径还是antMatcher风格的路径
    for (String path : securityProperties.getAuth().getPermitAllPath()) {
        String realPath = StrUtil.concat(basePath, path);
        // 先加入到允许路径中
        permitPaths.add(realPath);
        basePermitPaths.add(realPath);
    }
    String errorPath = StrUtil.concat(basePath, PropertyUtil.get(PropertyKey.Web.ERROR_PATH));
    // 错误路径也加入到允许路径中
    permitPaths.add(errorPath);
    basePermitPaths.add(errorPath);
    // 找出所有端点的url
    MVCUtil.requestMappingHandlerMappingStream().map((iter) -> iter.getHandlerMethods().entrySet()).flatMap(Collection::stream).forEach((entry) -> {
        // 获取该端点的路径
        String requestPath = StrUtil.concat(basePath, entry.getKey().getPatternsCondition().getPatterns().iterator().next());
        // 直接判断该路径是否需要验证,如果与免验证路径匹配则加入不需要验证路径,否则加入需要验证路径中
        for (String path : basePermitPaths) {
            if (matcher.match(path, requestPath)) {
                permitPaths.add(requestPath);
                return;
            }
        }
        needVerifyPaths.add(requestPath);
    });
    replacedert.notNull(matcher, "matcher must not be null");
    replacedert.notNull(needVerifyPaths, "needVerifyPaths must not be null");
    replacedert.notNull(permitPaths, "permitPaths must not be null");
    replacedert.notNull(basePermitPaths, "basePermitPaths must not be null");
    checkCorrectPermissions(securityProperties);
}

10 View Source File : ImageValidateFilter.java
License : GNU General Public License v3.0
Project Creator : Exrick

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    // 判断URL是否需要验证
    Boolean flag = false;
    String requestUrl = request.getRequestURI();
    for (String url : captchaProperties.getImage()) {
        if (pathMatcher.match(url, requestUrl)) {
            flag = true;
            break;
        }
    }
    if (flag) {
        String captchaId = request.getParameter("captchaId");
        String code = request.getParameter("code");
        if (StrUtil.isBlank(captchaId) || StrUtil.isBlank(code)) {
            ResponseUtil.out(response, ResponseUtil.resultMap(false, 500, "请传入图形验证码所需参数captchaId或code"));
            return;
        }
        String redisCode = redisTemplate.get(captchaId);
        if (StrUtil.isBlank(redisCode)) {
            ResponseUtil.out(response, ResponseUtil.resultMap(false, 500, "验证码已过期,请重新获取"));
            return;
        }
        if (!redisCode.toLowerCase().equals(code.toLowerCase())) {
            log.info("验证码错误:code:" + code + ",redisCode:" + redisCode);
            ResponseUtil.out(response, ResponseUtil.resultMap(false, 500, "图形验证码输入错误"));
            return;
        }
        // 已验证清除key
        redisTemplate.delete(captchaId);
        // 验证成功 放行
        chain.doFilter(request, response);
        return;
    }
    // 无需验证 放行
    chain.doFilter(request, response);
}

See More Examples