如何判断请求url中是否存在@pathvariable?

i2byvkas  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(510)

我正在尝试在网关上编写api权限筛选器。应该禁止不带有特定角色的令牌访问资源。除了包含 @PathVariable 参数。例如,具有uri的api /api/v1/query/{id} ,参数 id 可能是个问题 uuid 在某些情况下,可能是 long 其他情况下的价值。除了添加越来越多的regex模式,还有更好的方法吗?gateway的总体目标是消耗尽可能少的时间。

6l7fqoea

6l7fqoea1#

不管怎样,我还是想出了一个合适的解决办法。这个 @PathVariable 在所有项目中都位于url的最后或最后两部分。例如 /api/v1/data/query/{uid}/{pid} 或者类似的。所以我们可以用ApacheCommon的 StringUtils#lastIndexOf() 以及 StringUtils#substring() .
要编写用于演示的代码,请同时导入hutool和commons-lang3。

<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.5.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.11</version>
        </dependency>
import cn.hutool.core.util.IdUtil;
import org.apache.commons.lang3.StringUtils;

public class StringDemo {
    public static void main(String[] args) {
        String url = "http://localhost:8080/api/v1/data/query/" + IdUtil.simpleUUID() + "/" + IdUtil.getSnowflake(1L, 16).nextId();
        System.out.println(url);
        int index = StringUtils.lastIndexOf(url, "/");
        String subUrl = StringUtils.substring(url, 0, index);
        System.out.println(subUrl);
        int index2 = StringUtils.lastIndexOf(subUrl, "/");
        String subOfSubUrl = StringUtils.substring(url, 0, index2);
        System.out.println(subOfSubUrl);
    }
}

结果如下:

http://localhost:8080/api/v1/data/query/19280769925f43d98b2af405579955ac/1356927788629626880
http://localhost:8080/api/v1/data/query/19280769925f43d98b2af405579955ac
http://localhost:8080/api/v1/data/query

通过将uri简化为最简单的,在我的例子中是 /api/v1/data/query ,很容易编写相关代码来检查角色。

相关问题