You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "myselfuser1 (via GitHub)" <gi...@apache.org> on 2025/01/29 09:51:02 UTC

[I] How to Get Keycloak User Roles After Integrating Single Sign On with Keycloak [superset]

myselfuser1 opened a new issue, #32023:
URL: https://github.com/apache/superset/issues/32023

   ### Bug description
   
   Here is the code from `superset_config.py`
   
   ```
   SECRET_KEY = 'my_secret_key'
   AUTH_TYPE = AUTH_OAUTH
   LOGOUT_REDIRECT_URL='https://localhost:3000/auth/realms/master/protocol/openid-connect/logout'
   AUTH_USER_REGISTRATION = True
   # AUTH_USER_REGISTRATION_ROLE = "Gamma"
   OAUTH_PROVIDERS = [
       {
           'name': 'keycloak',
           'token_key': 'access_token',
           'icon': 'fa-key',
           'remote_app': {
               'client_id': 'MY_CLIENT_ID',  # Replace with your Keycloak client ID
               'client_secret': 'MY_CLIENT_SECRET',  # Replace with your Keycloak client secret
               'api_base_url': 'https://localhost:3000/auth/realms/master/protocol/openid-connect/',  # Replace with your Keycloak realm URL
               'client_kwargs': {
                   'scope': 'openid profile email',
                   'roles_key': 'realm_access.roles',
               },
               'server_metadata_url': 'https://localhost:3000/realms/master/.well-known/openid-configuration',
               'api_base_url': 'https://localhost:3000/realms/master/protocol/',
               'access_token_url': 'https://localhost:3000/auth/realms/master/protocol/openid-connect/token',  # Replace with your Keycloak token URL
               'authorize_url': 'https://localhost:3000/auth/realms/master/protocol/openid-connect/auth',  # Replace with your Keycloak authorization URL
               'jwks_uri': 'https://localhost:3000/auth/realms/master/protocol/openid-connect/certs',  # Replace with your Keycloak JWKS URI
           },
       }
   ]
   AUTH_ROLES_SYNC_AT_LOGIN = True
   
   JWT_ALGORITHM = "RS256"
   # URL to the public key endpoint
   public_key_url = "https://localhost:3000/auth/realms/master"
   
   
   def fetch_keycloak_rs256_public_cert():
       with urllib.request.urlopen(public_key_url) as response:  # noqa: S310
           public_key_url_response = json.load(response)
       public_key = public_key_url_response["public_key"]
       if public_key:
           pem_lines = [
               "-----BEGIN PUBLIC KEY-----",
               public_key,
               "-----END PUBLIC KEY-----",
           ]
           cert_pem = "\n".join(pem_lines)
       else:
           cert_pem = "No cert found"
       return cert_pem
   
   print("aaaaa")
   JWT_PUBLIC_KEY = fetch_keycloak_rs256_public_cert()
   print("bbbbbb")
   AUTH_ROLES_MAPPING = {
       'Super Admin': ['Admin', 'sql_lab'],
       'Portal Admin': ['Admin',],
       'Company Admin': ['Admin',],
       'Admin': ['Admin',],
       'admin': ['Admin',],
       'Non C-Cash User': ['Public'],
       'Ex C-Cash User': ['Public'],
       'External Users': ['Public'],
       'Licensed C-Cash User': ['Alpha'],
       'C-Cash User': ['Gamma'],
   }
   AUTH_ROLES_SYNC_AT_LOGIN = True
   AUTH_USER_REGISTRATION = True
   AUTH_USER_REGISTRATION_ROLE = "Public"
   
   class CustomSsoSecurityManager(SupersetSecurityManager):
       def oauth_user_info(self, provider, response=None):  # noqa: ARG002
           me = self.appbuilder.sm.oauth_remotes[provider].get("openid-connect/userinfo")
           me.raise_for_status()
           data = me.json()
           logging.debug("User info from Keycloak: %s", data)
           return {
               "username": data.get("preferred_username", ""),
               "first_name": data.get("given_name", ""),
               "last_name": data.get("family_name", ""),
               "email": data.get("email", ""),
               "role_keys": data.get("role_keys", []),
           }
   
       def load_user_jwt(self, _jwt_header, jwt_data):
           username = jwt_data["preferred_username"]
           user = self.find_user(username=username)
           if user.is_active:
               # Set flask g.user to JWT user, we can't do it on before request
               g.user = user
               return user
           return None
   
   CUSTOM_SECURITY_MANAGER = CustomSsoSecurityManager
   ```
   
   
   
   ### Screenshots/recordings
   
   Every time i sign in , the public role is assigned to the user on superset irrespective of what role is present for that user in keycloak
   
   ### Superset version
   
   master / latest-dev
   
   ### Python version
   
   3.9
   
   ### Node version
   
   16
   
   ### Browser
   
   Chrome
   
   ### Additional context
   
   _No response_
   
   ### Checklist
   
   - [x] I have searched Superset docs and Slack and didn't find a solution to my problem.
   - [x] I have searched the GitHub issue tracker and didn't find a similar bug report.
   - [x] I have checked Superset's logs for errors and if I found a relevant Python stacktrace, I included it here as text in the "additional context" section.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [I] How to Get Keycloak User Roles After Integrating Single Sign On with Keycloak [superset]

Posted by "dosubot[bot] (via GitHub)" <gi...@apache.org>.
dosubot[bot] commented on issue #32023:
URL: https://github.com/apache/superset/issues/32023#issuecomment-2621265468

   <!-- Answer -->
   To correctly extract roles from the Keycloak response, you need to ensure that the roles are included in the response from Keycloak. It seems that the current response does not include any roles. Here are some steps you can take:
   
   1. **Configure Keycloak to Include Roles**: In Keycloak, you need to configure the client to include roles in the token or userinfo response. This can typically be done by adding a mapper in the Keycloak client settings. You can add a "User Realm Role" or "User Client Role" mapper to include roles in the token.
   
   2. **Update `oauth_user_info` Method**: Once roles are included in the response, update the `oauth_user_info` method to extract the roles from the correct field. For example, if roles are included under `realm_access` in the token, you might access them like this:
   
      ```python
      roles = data.get('realm_access', {}).get('roles', [])
      ```
   
   3. **Verify Role Mapping**: Ensure that the roles extracted from Keycloak match the roles defined in your `AUTH_ROLES_MAPPING` configuration.
   
   By configuring Keycloak to include roles and updating your code to extract them correctly, you should be able to map Keycloak roles to Superset roles effectively.
   
   
   <!-- Dosu Comment Footer -->
   *To continue talking to [Dosu](https://dosu.dev), mention @dosu.*
   
   ---
   <sup>Help Dosu learn! Give it feedback: [Great Response](https://app.dosu.dev/response-feedback/5b831651-542f-447b-8c38-8153f96b3b95?feedback_type=great_response) | [Irrelevant Answer](https://app.dosu.dev/response-feedback/5b831651-542f-447b-8c38-8153f96b3b95?feedback_type=irrelevant_answer) | [Incorrect Sources](https://app.dosu.dev/response-feedback/5b831651-542f-447b-8c38-8153f96b3b95?feedback_type=incorrect_sources) | [Too Verbose](https://app.dosu.dev/response-feedback/5b831651-542f-447b-8c38-8153f96b3b95?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/5b831651-542f-447b-8c38-8153f96b3b95?feedback_type=hallucination) | [Other](https://app.dosu.dev/response-feedback/5b831651-542f-447b-8c38-8153f96b3b95?feedback_type=other)</sup>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [I] How to Get Keycloak User Roles After Integrating Single Sign On with Keycloak [superset]

Posted by "myselfuser1 (via GitHub)" <gi...@apache.org>.
myselfuser1 commented on issue #32023:
URL: https://github.com/apache/superset/issues/32023#issuecomment-2621263392

   @dosu when i print `data = me.json()` i get this ```
   {'sub': '182345b0-c8a1-1233-2da2-c22afe2b882c', 'email_verified': True, 
       'name': 'Abc def', 'preferred_username': 'abc@gmail.com',
    'given_name': 'Abc', 'family_name': 'def', 'email': 'abc@gmail.com'}
   ```
   
   there is no `role_keys`


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [I] How to Get Keycloak User Roles After Integrating Single Sign On with Keycloak [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas closed issue #32023: How to Get Keycloak User Roles After Integrating Single Sign On with Keycloak
URL: https://github.com/apache/superset/issues/32023


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [I] How to Get Keycloak User Roles After Integrating Single Sign On with Keycloak [superset]

Posted by "dosubot[bot] (via GitHub)" <gi...@apache.org>.
dosubot[bot] commented on issue #32023:
URL: https://github.com/apache/superset/issues/32023#issuecomment-2621162131

   <!-- Answer -->
   To ensure that the correct Keycloak user roles are assigned in Superset after integrating Single Sign-On with Keycloak, you need to map the roles from Keycloak to Superset roles using the `AUTH_ROLES_MAPPING` configuration. It seems like you have already set up the `AUTH_ROLES_MAPPING` in your `superset_config.py`, but the issue might be with how the roles are being extracted and used.
   
   Here are a few things to check and adjust:
   
   1. **Role Extraction**: In your `CustomSsoSecurityManager`, ensure that the roles are being correctly extracted from the Keycloak response. The `oauth_user_info` method should extract the roles from the correct field in the Keycloak response. It seems like you are using `role_keys`, but you should verify that this is the correct field in the Keycloak response.
   
   2. **Role Mapping**: Make sure that the roles you are mapping in `AUTH_ROLES_MAPPING` match exactly with the roles being sent by Keycloak. Any mismatch in role names will result in the default role being assigned.
   
   3. **Debugging**: Add logging to verify what roles are being received from Keycloak and how they are being processed. This can help identify if the roles are being correctly extracted and mapped.
   
   4. **Sync at Login**: Since you have `AUTH_ROLES_SYNC_AT_LOGIN` set to `True`, roles should be synced at every login. Ensure that this setting is being respected by checking the logs for any errors during the login process.
   
   If these steps do not resolve the issue, you might want to review similar discussions for additional insights. For instance, there is an open discussion on [Assigning Superset roles to Keycloak authenticated users using the AUTH_ROLES_MAPPING](https://github.com/apache/superset/discussions/27902) that might provide more context or solutions <sup>[[1]](https://github.com/apache/superset/discussions/27902)</sup>.
   
   
   <!-- Dosu Comment Footer -->
   *To continue talking to [Dosu](https://dosu.dev), mention @dosu.*
   
   ---
   <sup>Help Dosu learn! Give it feedback: [Great Response](https://app.dosu.dev/response-feedback/7ca6fb7b-d051-4d26-a079-5366cd6adf50?feedback_type=great_response) | [Irrelevant Answer](https://app.dosu.dev/response-feedback/7ca6fb7b-d051-4d26-a079-5366cd6adf50?feedback_type=irrelevant_answer) | [Incorrect Sources](https://app.dosu.dev/response-feedback/7ca6fb7b-d051-4d26-a079-5366cd6adf50?feedback_type=incorrect_sources) | [Too Verbose](https://app.dosu.dev/response-feedback/7ca6fb7b-d051-4d26-a079-5366cd6adf50?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/7ca6fb7b-d051-4d26-a079-5366cd6adf50?feedback_type=hallucination) | [Other](https://app.dosu.dev/response-feedback/7ca6fb7b-d051-4d26-a079-5366cd6adf50?feedback_type=other)</sup>
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org