我的架构中有几个微服务。我想要实现一个API网关来将请求路由到服务。为此,我实现了spring-cloud-gateway,这是我的application.yml
server:
port: 9090
spring:
application:
name: "API-GATEWAY"
cloud:
gateway:
routes:
- id: task-service
uri: 'http://localhost:8083'
predicates:
- Path=/task/**到目前为止,一切都如期而至。请求localhost:9090/task/123是对localhost:8083/task/123的请求。这是第二部分。
我希望一些用户只访问一些端点。在我的JWT令牌中,我有一个角色字段。
{
"accountName": "erdem.ontas",
"surname": "Öntaş",
"roles": [
"ADMIN",
"USER"
],
}我不想在每个服务中单独指定授权,在spring云网关中有任何方法来指定基于角色的访问吗?例如,我希望用户角色能够访问GET http://localhost:9090/task/,但不能访问GET http://localhost:9090/dashboard/
发布于 2022-05-26 12:32:01
如果您做了,而不是想要并需要创建完整的OAuth 2服务器/客户端基础设施,并且希望保持简单,只需创建一个自定义GatewayFilter,其中只需检查从标头中提取的OAuth令牌是否具有预先配置的角色。所以从一个简单的GatewayFilter开始
@Component
public class RoleAuthGatewayFilterFactory extends
AbstractGatewayFilterFactory<RoleAuthGatewayFilterFactory.Config> {
public RoleAuthGatewayFilterFactory() {
super(Config.class);
}
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
var request = exchange.getRequest();
// JWTUtil can extract the token from the request, parse it and verify if the given role is available
if(!JWTUtil.hasRole(request, config.getRole())){
// seems we miss the auth token
var response = exchange.getResponse();
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return response.setComplete();
}
return chain.filter(exchange);
};
}
@Data
public static class Config {
private String role;
}
@Override
public List<String> shortcutFieldOrder() {
// we need this to use shortcuts in the application.yml
return Arrays.asList("role");
}
}在这里,我们只创建一个简单的过滤器,它从config (application.yml)接收所需的角色,并检查请求是否被授权继续。
要使用过滤器,只需将filters添加到路由配置中即可。
server:
port: 9090
spring:
application:
name: "API-GATEWAY"
cloud:
gateway:
routes:
- id: task-service
uri: 'http://localhost:8083'
filters:
- RoleAuth=ADMIN
predicates:
- Path=/task/**这样,RoleAuth过滤器就可以在几个路由上被重用。
https://stackoverflow.com/questions/72310917
复制相似问题