Skip to content

For the complete documentation index, see llms.txt. Markdown versions of all docs pages are available by appending .md to any docs URL.

Authorization code flow

Page as Markdown

Redirect browser users to Microsoft Entra ID to log in, then store their tokens in session cookies.

Protect a route with the OAuth2 authorization code flow. When a browser request is unauthenticated, the gateway redirects it to Microsoft Entra ID. After login, the gateway exchanges the authorization code for tokens and stores them in session cookies. Your upstream service does not need to handle the OAuth2 flow.

Before you begin

  1. Complete the Microsoft Entra ID setup page. This flow needs the Entra ID App Registration, the test user, the API scope, the Backend, and the BackendConfigPolicy that it creates.

  2. Make sure your gateway has an HTTPS listener. Kgateway marks the OAuth2 nonce and code verifier cookies as Secure, so browsers do not send them over HTTP. Without those cookies, callback validation fails. To add an HTTPS listener, see HTTPS listener. The access token validation flow works over HTTP because it does not use cookies.

Configure the authorization code flow

Create the Kubernetes Secret that holds the Entra ID client secret, a GatewayExtension that configures the provider, and a TrafficPolicy that enforces the flow on a route.

  1. Create a Kubernetes Secret with the Entra ID client secret. Replace YOUR_CLIENT_SECRET with the value that you copied from the Certificates & secrets section of your App Registration during Entra ID setup.

    kubectl create secret generic entra-id-client-secret \
      --from-literal=client-secret=YOUR_CLIENT_SECRET \
      -n kgateway-system
  2. Create a GatewayExtension that holds everything the gateway needs to talk to Entra ID.

    kubectl apply -f- <<EOF
    apiVersion: gateway.kgateway.dev/v1alpha1
    kind: GatewayExtension
    metadata:
      name: entra-id-oauth2
      namespace: kgateway-system
    spec:
      oauth2:
        backendRef:
          group: gateway.kgateway.dev
          kind: Backend
          name: entra-id
          namespace: kgateway-system
        issuerURI: https://sts.windows.net/YOUR_TENANT_ID/
        authorizationEndpoint: https://login.microsoftonline.com/YOUR_TENANT_ID/oauth2/v2.0/authorize
        tokenEndpoint: https://login.microsoftonline.com/YOUR_TENANT_ID/oauth2/v2.0/token
        endSessionEndpoint: https://login.microsoftonline.com/YOUR_TENANT_ID/oauth2/v2.0/logout
        redirectURI: https://www.example.com/oauth2/redirect
        scopes:
          - openid
          - email
          - profile
          - api://YOUR_CLIENT_ID/access_as_user
        credentials:
          clientID: YOUR_CLIENT_ID
          clientSecretRef:
            name: entra-id-client-secret
    EOF

    Replace YOUR_TENANT_ID and YOUR_CLIENT_ID with the values that you copied in Entra ID setup.

    FieldDescription
    backendRefPoints to the Backend from Entra ID setup. Kgateway uses it to reach Entra ID for the token exchange.
    issuerURITriggers OIDC discovery of the endpoints. Because this example sets authorizationEndpoint, tokenEndpoint, and endSessionEndpoint explicitly, the explicit values win and kgateway skips discovery.
    authorizationEndpointThe Entra ID endpoint that the gateway redirects browser users to for login.
    tokenEndpointThe Entra ID endpoint that the gateway calls to exchange the authorization code for tokens.
    redirectURIThe callback URL that kgateway sends to Entra ID as the redirect_uri parameter. This value must exactly match the redirect URI in your App Registration.
    scopesMust include openid for OIDC. To use the access token from this flow with the access token validation flow, include your custom scope, such as api://{client-id}/access_as_user.
    endSessionEndpointHandles single logout. When a user goes to /logout, kgateway clears the session cookies and sends the browser to this URL so that Entra ID ends its session too.
    clientSecretRef.nameMust match the Secret name from the previous step. Kgateway reads the client-secret key inside that Secret.
  3. Create a TrafficPolicy that references the extension by name.

    Warning

    The OAuth2 filter does not protect against CSRF attacks on routes with cached authentication cookies. Pair it with a CSRFPolicy on the same route.

    kubectl apply -f- <<EOF
    apiVersion: gateway.kgateway.dev/v1alpha1
    kind: TrafficPolicy
    metadata:
      name: entra-id-oauth2-policy
      namespace: httpbin
    spec:
      targetRefs:
        - group: gateway.networking.k8s.io
          kind: HTTPRoute
          name: httpbin
      oauth2:
        extensionRef:
          name: entra-id-oauth2
          namespace: kgateway-system
    EOF
  4. Verify that the policy is attached to the route.

    kubectl get TrafficPolicy entra-id-oauth2-policy -n httpbin -o yaml

    In the status.ancestors section, confirm that both the Accepted and Attached conditions are True.

Verify

  1. Send a request without a session cookie. The gateway redirects to Entra ID.

    curl -vik "https://${INGRESS_GW_ADDRESS}:8443/headers" -H "host: www.example.com"

    Example output. The redirect_uri parameter matches the value registered on the Entra ID App Registration.

    < HTTP/2 302
    < location: https://login.microsoftonline.com/YOUR_TENANT_ID/oauth2/v2.0/authorize?client_id=YOUR_CLIENT_ID&...&redirect_uri=https%3A%2F%2Fwww.example.com%2Foauth2%2Fredirect
    < set-cookie: OauthNonce-...;path=/;Max-Age=600;secure;HttpOnly
  2. Open a browser and go to your protected route, such as https://www.example.com/headers. The gateway redirects you to the Microsoft login page.

  3. Log in with the test user credentials you created in the Entra ID setup.

  4. Verify that Entra ID returns you to the route and that the response shows the httpbin output.

    If you get a 401 response with CSRF token validation failed in the gateway logs, you sent the request over HTTP. Retry over HTTPS.

    If Entra ID shows AADSTS50011: The redirect URI ... specified in the request does not match the redirect URIs configured for the application, the redirectURI on the GatewayExtension does not match what is registered in your App Registration.

Cleanup

You can remove the resources that you created in this guide.
kubectl delete TrafficPolicy entra-id-oauth2-policy -n httpbin
kubectl delete GatewayExtension entra-id-oauth2 -n kgateway-system
kubectl delete secret entra-id-client-secret -n kgateway-system

To remove Entra ID and the shared resources, see the Cleanup section of the Entra ID setup page.

Was this page helpful?