hyperdude2022

Untitled

Mar 13th, 2023
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. import requests
  2. import json
  3. import boto3
  4.  
  5. # Set up variables for Keycloak server URL and admin credentials
  6. keycloak_url = 'https://mykeycloak/auth'
  7. realm_name = 'myrealm'
  8. client_id = 'admin-cli'
  9. admin_username = 'admin'
  10. admin_secret_name = 'meysecretkey'
  11. identity_provider_alias = 'auth0' # Change this to the alias of your identity provider
  12. mapper_name = 'my_mapper' # Change this to the name of your mapper
  13. mapper_config = {
  14. 'userinfo.token.claim': 'true',
  15. 'userinfo.token.claim.name': 'my_claim_name'
  16. }
  17.  
  18. # Retrieve admin password from AWS Secrets Manager
  19. secrets_manager = boto3.client('secretsmanager', region_name='eu-west-1')
  20. try:
  21. admin_secret = secrets_manager.get_secret_value(SecretId=admin_secret_name)
  22. admin_password = admin_secret['SecretString']
  23. except Exception as e:
  24. print(f'Error retrieving secret: {e}')
  25. exit(1)
  26.  
  27. # Authenticate with Keycloak server to obtain access token for admin user
  28. token_url = f'{keycloak_url}/realms/master/protocol/openid-connect/token'
  29. token_data = {
  30. 'grant_type': 'password',
  31. 'client_id': client_id,
  32. 'username': admin_username,
  33. 'password': admin_password
  34. }
  35. response = requests.post(token_url, data=token_data)
  36.  
  37. if response.status_code == 200:
  38. admin_access_token = response.json()['access_token']
  39. else:
  40. raise Exception(f'Failed to authenticate. Response status code: {response.status_code}')
  41.  
  42. # Add mapper to the identity provider
  43. identity_provider_url = f'{keycloak_url}/admin/realms/{realm_name}/identity-provider/instances/{identity_provider_alias}'
  44. mapper_url = f'{identity_provider_url}/mappers'
  45. headers = {'Authorization': f'Bearer {admin_access_token}', 'Content-Type': 'application/json'}
  46. mapper_data = {
  47. "name": "Test10",
  48. "identityProviderAlias": "auth0",
  49. "identityProviderMapper": "oidc-advanced-role-idp-mapper",
  50. "config": {
  51. "syncMode": "FORCE",
  52. "role": "test role",
  53. "key": "duckduck",
  54. "claim.value.regex": "^admin.*"
  55. }
  56. }
  57.  
  58. response = requests.post(mapper_url, json=mapper_data, headers=headers)
  59.  
  60. if response.status_code == 201:
  61. print(f'Mapper {mapper_name} added successfully to identity provider {identity_provider_alias}')
  62. else:
  63. raise Exception(f'Failed to add mapper. Response status code: {response.status_code}')
  64.  
Add Comment
Please, Sign In to add comment