Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Gateway API
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[Istio] Custom Authorization with Istio

Posted on October 19, 2025October 19, 2025 By nim No Comments on [Istio] Custom Authorization with Istio

Tôi sẽ cung cấp cho bạn AuthorizationPolicy tối thiểu cần thiết để gọi nhà cung cấp của bạn, cùng với các biến thể phạm vi tùy chọn và một ghi chú để sửa máy chủ dịch vụ của nhà cung cấp.

Contents

Toggle
  • Use the custom provider in an AuthorizationPolicy
  • Important: fix provider “service” host
  • Quick verify

Use the custom provider in an AuthorizationPolicy

  • Mesh-wide (applies to all workloads):
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: use-ext-authz-mesh
  namespace: istio-system
spec:
  action: CUSTOM
  provider:
    name: my-external-authz-provider
  rules:
  - {}
  • Namespace-wide (replace default with your namespace):
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: use-ext-authz-namespace
  namespace: default
spec:
  action: CUSTOM
  provider:
    name: my-external-authz-provider
  rules:
  - {}
  • Single workload (label app: httpbin as example):
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: use-ext-authz-workload
  namespace: default
spec:
  selector:
    matchLabels:
      app: httpbin
  action: CUSTOM
  provider:
    name: my-external-authz-provider
  rules:
  - {}
  • Giải thích: action: CUSTOM với provider.name: my-external-authz-provider báo cho Istio biết để định tuyến các yêu cầu phù hợp đến máy chủ gRPC ext-authz Envoy của bạn. Sử dụng rules: – {} áp dụng cho tất cả các yêu cầu trong phạm vi đã chọn.

Important: fix provider “service” host

  • Recommended (use a resolvable host). Nếu đang chạy trong cluster, hãy tham chiếu đến K8s Service FQDN:
extensionProviders:
- name: my-external-authz-provider
  envoyExtAuthzGrpc:
    service: ext-authz.istio-system.svc.cluster.local
    port: "9000"

If the server is external, create a ServiceEntry (and disable TLS if your server is plain gRPC):

apiVersion: networking.istio.io/v1beta1
kind: ServiceEntry
metadata:
  name: external-ext-authz
  namespace: istio-system
spec:
  hosts:
345678
  ports:
  - number: 9000
    name: grpc
    protocol: GRPC
  resolution: STATIC
  endpoints:
  - address: 192.168.101.23
---
apiVersion: networking.istio.io/v1beta1
kind: DestinationRule
metadata:
  name: external-ext-authz-dr
  namespace: istio-system
spec:
  host: ext-authz.external.svc.cluster.local
  trafficPolicy:
    tls:
      mode: DISABLE

Then point the provider at that host:

extensionProviders:
- name: my-external-authz-provider
  envoyExtAuthzGrpc:
    service: ext-authz.external.svc.cluster.local
    port: "9000"

Quick verify

  • Apply the AuthorizationPolicy in the desired scope.
  • Send a request through a sidecar-injected pod; you should see calls hitting your gRPC server (you already log metadata and the full CheckRequest).
  • Optionally, check the target pod’s istio-proxy logs for ext_authz activity.
  • Changes made earlier enable rich debugging in your Check handler, so you’ll see headers and attributes immediately.

Create Check Rrequest with golang:

// main.go
package main

import (
    "context"
    "fmt"
    "log"
    "net"

    "strings"

    statuspb "google.golang.org/genproto/googleapis/rpc/status"
    "google.golang.org/grpc"
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/metadata"
    "google.golang.org/grpc/peer"
    "google.golang.org/protobuf/encoding/protojson"

    // Import các định nghĩa proto của Envoy
    authv3 "github.com/envoyproxy/go-control-plane/envoy/service/auth/v3"
)

// Khai báo một struct để implement interface AuthorizationServer
type server struct{}

// Implement phương thức Check. Đây là nơi logic phân quyền của bạn được đặt.
func (s *server) Check(ctx context.Context, req *authv3.CheckRequest) (*authv3.CheckResponse, error) {
    // In ra để debug. Trong thực tế, bạn sẽ dùng logger có cấu trúc.
    log.Println("--> New request to Authorizer")

    // Log gRPC metadata và thông tin peer (địa chỉ client, TLS... nếu có)
    if md, ok := metadata.FromIncomingContext(ctx); ok {
        log.Printf("gRPC metadata: %v", md)
    }
    if p, ok := peer.FromContext(ctx); ok {
        log.Printf("peer: addr=%v authInfo=%T", p.Addr, p.AuthInfo)
    }

    // Pretty-print toàn bộ CheckRequest để debug nhanh mọi thuộc tính
    if b, err := (protojson.MarshalOptions{Indent: "  "}).Marshal(req); err != nil {
        log.Printf("failed to marshal CheckRequest: %v", err)
    } else {
        log.Printf("CheckRequest JSON:\n%s", b)
    }

    // Lấy các thuộc tính của request từ payload mà Envoy gửi đến
    httpRequest := req.GetAttributes().GetRequest().GetHttp()
    method := httpRequest.GetMethod()
    requestPath := httpRequest.GetPath()
    if i := strings.IndexByte(requestPath, '?'); i >= 0 { // bỏ phần query nếu có
        requestPath = requestPath[:i]
    }

    // ----- LOGIC PHÂN QUYỀN: chỉ cho phép GET /ip -----
    if strings.EqualFold(method, "GET") && requestPath == "/ip" {
        log.Println("Request is ALLOWED: GET /ip")
        return &authv3.CheckResponse{
            Status: &statuspb.Status{
                Code: int32(codes.OK),
            },
        }, nil
    }

    // ----- NẾU KHÔNG THỎA MÃN -----
    log.Printf("Request is DENIED: method=%s path=%s", method, requestPath)
    // Nếu bị từ chối, trả về Status PermissionDenied.
    // Envoy sẽ chuyển đổi nó thành mã lỗi HTTP 403 Forbidden.
    return &authv3.CheckResponse{
        Status: &statuspb.Status{
            Code:    int32(codes.PermissionDenied),
            Message: fmt.Sprintf("Access Denied: only GET /ip allowed (got %s %s)", method, requestPath),
        },
    }, nil
}

func main() {
    // Khởi tạo một gRPC server mới.
    grpcServer := grpc.NewServer()

    // Đăng ký implement của bạn với gRPC server.
    authv3.RegisterAuthorizationServer(grpcServer, &server{})

    // Lắng nghe trên cổng 9000
    port := 9000
    lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }

    log.Printf("Starting gRPC server on port %d", port)
    if err := grpcServer.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %s", err)
    }
}
Golang, Kubernetes & Container

Post navigation

Previous Post: [Coralogix] DataPrime Query on Coralogix
Next Post: [Laravel/Azure] Login with Azure account on Laravel

More Related Articles

[Golang] Create Your Own CLI — With Golang Golang
[go-git] returned a non-zero code: 1 when building docker Golang
[Golang/Container] Build docker/container Golang Coding
 [Goland] Install GCC Compiler On Windows OS Golang
[Jenkins] Hướng dẫn sử dụng Jenkins pipeline to control Jenkins agent in k8s and deploy on k8s CI/CD
[wordpress] Install WordPress so easily. Kubernetes & Container

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [Rancher/EKS] Rancher from v2.12.x can not work on eks cluster. April 15, 2026
  • [Telegram/Openclaw] Configure openclaw bot in a Telegram group. March 31, 2026
  • Tutorial: Gateway API + Traefik + oauth2-proxy (Microsoft Entra ID) March 30, 2026
  • Full + incremental backup: When restoring, do deleted files come back? March 27, 2026
  • [K8S] Create long-lived kubeconfig on k8s March 23, 2026

Archives

  • April 2026
  • March 2026
  • February 2026
  • January 2026
  • December 2025
  • November 2025
  • October 2025
  • September 2025
  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • AI
    • OpenClaw
  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Gateway API
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2026 NimTechnology.