簡體   English   中英

我可以使用 Spring Cloud Gateway 進行基於角色的授權嗎?

[英]Can I use Spring Cloud Gateway for role based authorization?

我的架構中有幾個微服務。 我想實現一個 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-cloud-gateway 中指定基於角色的訪問? 例如,我希望 USER 角色能夠訪問GET http://localhost:9090/task/但不能訪問GET http://localhost:9090/dashboard/

如果您不想並且需要創建完整的 OAuth 2 服務器/客戶端基礎架構並希望保持簡單,只需創建一個自定義GatewayFilter ,在其中檢查從標頭中提取的 JWT 令牌是否具有預配置的角色。 所以從一個簡單的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");
    }
}

在這里,我們只創建一個簡單的過濾器,它從配置(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過濾器可以在多個路由上重復使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM