Expose and secure a workload with OAuth2

This tutorial shows how to expose and secure services or Functions using API Gateway Controller. The controller reacts to an instance of the APIRule custom resource (CR) and creates an Istio VirtualService and Oathkeeper Access Rules according to the details specified in the CR. To interact with the secured services, the tutorial uses an OAuth2 client registered through the Hydra Maester controller.

You can use it as a follow-up to the Set up a custom domain for a workload tutorial.


This tutorial is based on a sample HttpBin service deployment and a sample Function. To deploy or create one of those, follow the Create a workload tutorial.

Register an OAuth2 client and get tokens

  1. Export your client as an environment variable:

    Click to copy
  2. Create an OAuth2 client with "read" and "write" scopes. Run:

    Click to copy
    cat <<EOF | kubectl apply -f -
    apiVersion: hydra.ory.sh/v1alpha1
    kind: OAuth2Client
    name: $CLIENT_NAME
    namespace: $NAMESPACE
    - "client_credentials"
    scope: "read write"
    secretName: $CLIENT_NAME
  3. Export the credentials of the created client as environment variables. Run:

    Click to copy
    export CLIENT_ID="$(kubectl get secret -n $NAMESPACE $CLIENT_NAME -o jsonpath='{.data.client_id}' | base64 --decode)"
    export CLIENT_SECRET="$(kubectl get secret -n $NAMESPACE $CLIENT_NAME -o jsonpath='{.data.client_secret}' | base64 --decode)"
  4. Encode your client credentials and export them as an environment variable:

    Click to copy
    export ENCODED_CREDENTIALS=$(echo -n "$CLIENT_ID:$CLIENT_SECRET" | base64)
  5. Get tokens to interact with secured resources using client credentials flow:

    • Token with "read" scope
    • Token with "write" scope

Expose and secure your workload

Follow the instructions in the tabs to expose an instance of the HttpBin service or a sample Function, and secure them with Oauth2 scopes.

  • HttpBin
  • Function

CAUTION: When you secure a workload, don't create overlapping Access Rules for paths. Doing so can cause unexpected behavior and reduce the security of your implementation.

Access the secured resources

Follow the instructions in the tabs to call the secured service or Functions using the tokens issued for the client you registered.

  • Call secured endpoints of a service
  • Call the secured Function

TIP: To learn more about the security options, read the document describing authorization configuration.