I am trying to write an api permission filter on gateway. Tokens that do not carry with the specific roles should be prohibited from accessing resources. All the requests have been filtered effectively, except for apis that contains @PathVariable
params. For example, an api with the URI /api/v1/query/{id}
, the param id
might be a uuid
in some cases, and may be a long
value in other cases.
Are there any better ways except adding more and more Regex patterns? The overall goal of gateway is to consume as less time as possible.
Asked
Active
Viewed 63 times
-1

Jimmy Jiang
- 1
- 1
- 7
-
You can supply your own `Converter` to `FormatterRegistry`. Check this out: https://www.baeldung.com/spring-mvc-custom-data-binder – Pranjal Gore Feb 03 '21 at 08:36
-
@PranjalGore That does not work in my situation as the code I am writing will run on the API Gateway, and the filtered Api list are not located in the same project. – Jimmy Jiang Feb 03 '21 at 11:09
1 Answers
0
I came up with a proper solution anyway. The @PathVariable
in all the projects are located in the last or the last two parts in the URL. e.g. /api/v1/data/query/{uid}/{pid}
or something like that. So we could eliminate that part using Apache Common's StringUtils#lastIndexOf()
and StringUtils#substring()
.
To write the code for demonstration, import both Hutool and 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);
}
}
The result is as follows:
http://localhost:8080/api/v1/data/query/19280769925f43d98b2af405579955ac/1356927788629626880
http://localhost:8080/api/v1/data/query/19280769925f43d98b2af405579955ac
http://localhost:8080/api/v1/data/query
By simplifying the uri to the simpliest, in my case is /api/v1/data/query
, it is easy to write the related codes to check of roles.

Jimmy Jiang
- 1
- 1
- 7