All Products
Search
Document Center

Alibaba Cloud Service Mesh:Integrate Keycloak with ASM to implement SSO

Last Updated:Jan 31, 2024

This topic describes how to implement single sign-on (SSO) to all the applications in a Service Mesh (ASM) instance by using self-managed Keycloak as the identity provider (IdP). You do not need to individually log on to each application in the ASM instance. Instead, you authorize the Keycloak IdP of the OpenID Connect (OIDC) client type by using the custom authorization service of ASM, and then use the authorized IdP for authentication. Authenticated requests are sent to the applications along with the user information in Keycloak.

Prerequisites

Concepts

Concept

Description

IdP

An IdP is a system that stores and verifies digital identities. For example, you can use an account and password to verify your identity. If you use an Alipay account and password to log on to Youku, Alipay is the IdP.

OIDC

OIDC is a standard identity authentication protocol based on the OAuth 2.0 protocol. For more information, see the OpenID official website.

Scope

Scope is a concept in OIDC. Each IdP stores various types of user information, such as email address. Each type corresponds to a scope. When you use an IdP to verify your identity to access an application, the application is allowed to obtain only the specified types of information.

Procedure

Step 1: Deploy a sample application and a Keycloak application

  • Create a YAML file that contains the following content and run the kubectl apply -n default -f xxx.yaml command to deploy an httpbin application in the default namespace of the Container Service for Kubernetes (ACK) cluster.

    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: httpbin
    ---
    apiVersion: v1
    kind: Service
    metadata:
      name: httpbin
      labels:
        app: httpbin
        service: httpbin
    spec:
      ports:
      - name: http
        port: 8000
        targetPort: 80
      selector:
        app: httpbin
    ---
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: httpbin
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: httpbin
          version: v1
      template:
        metadata:
          labels:
            app: httpbin
            version: v1
        spec:
          serviceAccountName: httpbin
          containers:
          - image: docker.io/kennethreitz/httpbin
            imagePullPolicy: IfNotPresent
            name: httpbin
            ports:
            - containerPort: 80
  • Create a YAML file that contains the following content and run the kubectl apply -n default -f xxx.yaml command to deploy a Keycloak application in the default namespace of the ACK cluster.

    apiVersion: v1
    kind: Service
    metadata:
      name: keycloak
      labels:
        app: keycloak
    spec:
      ports:
      - name: http
        port: 8080
        targetPort: 8080
      selector:
        app: keycloak
    ---
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: keycloak
      labels:
        app: keycloak
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: keycloak
      template:
        metadata:
          labels:
            app: keycloak
        spec:
          containers:
          - name: keycloak
            image: quay.io/keycloak/keycloak:latest
            args: ["start-dev"]
            env:
            - name: KEYCLOAK_ADMIN
              value: "admin"
            - name: KEYCLOAK_ADMIN_PASSWORD
              value: "admin"
            - name: KC_PROXY
              value: "edge"
            ports:
            - name: http
              containerPort: 8080
            readinessProbe:
              httpGet:
                path: /realms/master
                port: 8080

Step 2: Expose the httpbin and Keycloak applications to the Internet by using the ingress gateway

In this example, HTTPS port 443 is used for access to the httpbin application, and HTTP port 80 is used for access to the Keycloak console.

  1. Create a certificate named myexample-credential for the HTTPS service. For more information, see Use an ingress gateway to enable HTTPS.

  2. Create an Istio gateway and a virtual service in the ACK cluster by using the following YAML files to expose the Keycloak application to the Internet.

    • Create a YAML file that contains the following content to configure an Istio gateway for the ASM instance in the ASM console. For more information, see Manage Istio gateways.

      apiVersion: networking.istio.io/v1beta1
      kind: Gateway
      metadata:
        name: ingressgateway
        namespace: istio-system
      spec:
        selector:
          app: istio-ingressgateway //Make sure that the selector matches the ingress gateway 
        servers:
          - hosts:
              - '*'
            port:
              name: http-httpbin //Use HTTPS port 443 to access the httpbin application 
              number: 443
              protocol: HTTPS
            tls:
              credentialName: myexample-credential
              mode: SIMPLE
          - hosts:
              - '*'
            port:
              name: keycloak //Use HTTP port 80 to access the Keycloak console 
              number: 80
              protocol: HTTP
                                      
    • Add the following virtual service to the ASM instance. For more information, see Manage virtual services.

      apiVersion: networking.istio.io/v1beta1
      kind: VirtualService
      metadata:
        name: ingressgateway-vs
        namespace: istio-system
      spec:
        gateways:
          - ingressgateway
        hosts:
          - '*'
        http:
          - match:
              - port: 80
            name: keycloak
            route:
              - destination:
                  host: keycloak.default.svc.cluster.local
                  port:
                    number: 8080
          - name: httpbin
            route:
              - destination:
                  host: httpbin.default.svc.cluster.local
                  port:
                    number: 8000
  3. Enter http://${IP address of the ingress gateway} in the address bar of your browser to access the Keycloak application.

  4. Click Administration Console and log on to the Keycloak console by using the admin account and password that you specified when you deployed the Keycloak application.

Step 3: Configure Keycloak

  1. In the left-side navigation pane of the Keycloak console, click Master, and then click Create Realm.

  2. On the configuration page of the new realm, create a client, as shown in the following figures. 321322

  3. Create a user, as shown in the following figure. Click Save. 331

  4. On the User details page, click the Credentials tab.

  5. In the dialog box that appears, set a logon password. Click Save.

  6. Create a realm role, as shown in the following figure. Click Save. role

  7. On the User details page, click the Role mapping tab.

  8. On the Role mapping tab, click Assign role to assign the role to the user. 381

  9. Create a client scope, as shown in the following figure. Click Save. 391

  10. On the Client scopes page, click mappers, and add a mapper, as shown in the following figure. Click Save. 3101

  11. Click the Scope tab, select the role that you created in Substep 6, and then click Assign. 3111

  12. On the client setting page, click the Client scopes tab and then Add client scope. In the dialog box that appears, click Add. 3121

  13. On the details page of the oauth2-proxy client, click the Settings tab, set the Valid redirect URIs parameter, and then click Save. 3131

Note

In this example, only the Keycloak service uses the HTTP protocol, and all other services use HTTPS. Therefore, the format of a valid redirect URL is https://${IP address of the ingress gateway}/oauth2/callback.

Keycloak configuration is completed. You need to record the following information:

  • Realm ID: Test-oidc

  • Client ID: oauth2proxy

  • client secret on the Credentials tab of the client setting page

Step 4: Enable a custom authorization service and configure OIDC-based SSO in the ASM console

  1. Log on to the ASM console. In the left-side navigation pane, choose Service Mesh > Mesh Management.

  2. On the Mesh Management page, click the name of the ASM instance. In the left-side navigation pane, choose Mesh Security Center > Custom Authorization Service.

  3. On the Custom Authorization Service page, click Define Custom Authorization Service and click the OIDC Authz and Authn Service tab. Set the parameters and click Create.

    Define Custom Authorization Service

    Set the parameters in the above figure based on the information about the OIDC application that you created. You can redirect a logon attempt to the IP address of the ingress gateway. For more information about cookie secrets, see Generating a Cookie Secret.

    • IdP OIDC Issuer URI: http://${IP address of the ingress gateway}/realms/${ID of the realm created in Keycloak}.

    • ClientID and Client Secret: Use the parameter values that you recorded.

    • Scopes: OpenID is required in this parameter.

  4. Create a virtual service by using the following YAML template:

    apiVersion: networking.istio.io/v1beta1
    kind: VirtualService
    metadata:
      name: oauth2-vs
      namespace: istio-system
    spec:
      gateways:
        - ingressgateway
      hosts:
        - '*'
      http:
        - match:
            - uri:
                prefix: /oauth2
          name: oauth2
          route:
            - destination:
                host: asm-oauth2proxy-httpextauth-oidc.istio-system.svc.cluster.local
                port:
                  number: 4180
    Note
    • Replace the value of host in the route field with the name of the OAuth2 Proxy service that corresponds to istio-system namespace in your ACK cluster.

    • Do not route other virtual services to paths whose prefixes are /oauth2.

Step 5: Create an authorization policy

  1. On the Mesh Management page, click the name of the ASM instance. In the left-side navigation pane, choose Mesh Security Center > AuthorizationPolicy.

  2. On the AuthorizationPolicy page, click Create from YAML.

  3. On the Create page, select a namespace from the Namespace drop-down list, select a template from the Template drop-down list, copy the following content to the YAML code editor, and then click Create.

    apiVersion: security.istio.io/v1beta1
    kind: AuthorizationPolicy
    metadata:
      name: oidc
      namespace: istio-system
    spec:
      action: CUSTOM
      provider:
        name: httpextauth-oidc
      rules:
        - to:
            - operation:
                notPorts:
                  - '80'
      selector:
        matchLabels:
          istio: ingressgateway
    Note
    • The authorization policy specifies that all the requests except those sent to port 80 must be authenticated.

    • The provider name is the name of the associated custom authorization service. You can obtain the service name in the custom authorization service list.

Step 6: Verify SSO

  1. Visit ${IP address of the ingress gateway for external access:80} in a browser.

    Expected result:1If the page shown in the preceding figure appears, SSO takes effect.

  2. Click Sign in with OpenID Connect. On the page of logon with Keycloak, enter the test user name and password that you created in Step 3, and click the logon button.

    Expected result:httpbin

  3. Click Request inspection and then choose /headers > Try it out > Execute.

    Expected result:

  4. Parse the JSON Web Token (JWT) in the request after bearer authentication in the preceding step in JWT Debugger. For more information about JWT Debugger, see the JWT official website.

    Expected result:JWTInformation in the preceding figure appears after the JWT is parsed, including the user information stored in Keycloak. The JWT is verified by ASM.