class Keycloakconnector: keycloak_openid = None def __init__(self, serverurl, realm, clientid, secret): self.keycloak_openid = KeycloakOpenID(server_url=serverurl, client_id=clientid, realm_name=realm, client_secret_key=secret, verify=True) config_well_know = self.keycloak_openid.well_know() # print(config_well_know) def getToken(self, appID, api): token = self.keycloak_openid.token(username="", password="", grant_type=["client_credentials"]) token = token['access_token'] print("Access token = ") print(token) return token # Get JWT public key. def getJWTPublickey(self): cert = self.keycloak_openid.certs() if cert is None: return "" x5c = cert.get('keys')[0]['x5c'][0] x5c = '-----BEGIN CERTIFICATE-----\n' + x5c + '\n-----END CERTIFICATE-----' x509 = OpenSSL.crypto.load_certificate(FILETYPE_PEM, x5c) pubkey = x509.get_pubkey() pubkey = OpenSSL.crypto.dump_publickey(FILETYPE_PEM, pubkey).decode("utf-8") return pubkey
class _Keycloak(AuthProvider): f""" Redis key-value pair database implementation of KeyValueStore Defines methods for getting, deleting and putting key value pairs :param host, port, db (see also `https://github.com/andymccurdy/redis-py)` Example: ``` db = KeyValueDatabase.instance(provider='redis', host='localhost', port=6379, db=0) ``` """ def __init__(self, domain: Optional[str] = None, audience: Optional[str] = None): super().__init__() self._domain = domain or os.getenv('KEYCLOAK_DOMAIN') self._client_secret_key = os.getenv('KEYCLOAK_CLIENT_SECRET_KEY') self._client_secret_id = os.getenv('KEYCLOAK_CLIENT_SECRET_ID') self._realm = os.getenv('KEYCLOAK_REALM') self._audience = audience or os.getenv('XCUBE_HUB_OAUTH_AUD') self._algorithms = ["RS256"] if self._domain is None: raise Unauthorized(description="Keycloak error: Domain not set") if self._audience is None: raise Unauthorized(description="Keycloak error: Audience not set") self._keycloak_openid = KeycloakOpenID( server_url=f"https://{self._domain}/auth/", client_id=self._client_secret_id, realm_name=self._realm, client_secret_key=self._client_secret_key, verify=True) def get_email(self, claims): if 'email' not in claims: return "no email" return claims['email'] def verify_token(self, token: str) -> Dict: """ Get a key value :param token: :return: """ try: self._keycloak_openid.introspect(token) except KeycloakGetError as e: raise Unauthorized(description="invalid token: " + str(e)) certs = self._keycloak_openid.certs() rsa_key = {} for key in certs["keys"]: rsa_key = { "kty": key["kty"], "kid": key["kid"], "use": key["use"], "n": key["n"], "e": key["e"] } try: self._claims = self._keycloak_openid.decode_token(token=token, key=rsa_key) except Exception as e: raise Unauthorized(description=str(e)) return self._claims
class Keycloakconnector: keycloak_openid = None def __init__(self, serverurl, realm, clientid, secret): self.keycloak_openid = KeycloakOpenID(server_url=serverurl, client_id=clientid, realm_name=realm, client_secret_key=secret, verify=True) config_well_know = self.keycloak_openid.well_know() self.serverurl = serverurl self.realm = realm # print(config_well_know) def getToken(self, appID, api): token = self.keycloak_openid.token(username="", password="", grant_type=["client_credentials"]) token = token['access_token'] print("Access token = ") print(token) return token # Get JWT public key. def getJWTPublickey(self): cert = self.keycloak_openid.certs() if cert is None: return "" x5c = cert.get('keys')[0]['x5c'][0] x5c = '-----BEGIN CERTIFICATE-----\n' + x5c + '\n-----END CERTIFICATE-----' x509 = OpenSSL.crypto.load_certificate(FILETYPE_PEM, x5c) pubkey = x509.get_pubkey() pubkey = OpenSSL.crypto.dump_publickey(FILETYPE_PEM, pubkey).decode("utf-8") return pubkey def getClientRoles(self, clientid, daa_token): api_call_headers = { 'Authorization': 'Bearer ' + daa_token, 'cache-control': "no-cache", "Content-Type": "application/json", "charset": "utf-8" } roles = "" try: # get keycloak client representation (needed to get the value of id_of_client parameter) client_url = self.serverurl + "admin/realms/" + self.realm + "/clients?clientId=" + clientid client_rep = get(client_url, headers=api_call_headers) client_json = json.loads(client_rep.text) id_of_client = client_json[0]["id"] print(id_of_client) # get client roles roles_url = self.serverurl + "admin/realms/" + self.realm + "/clients/" + id_of_client + "/roles" roles_rep = get(roles_url, headers=api_call_headers) keycloak_roles = json.loads(roles_rep.text) if "can_id_read" in keycloak_roles[0]: can_id_read_array = keycloak_roles[0]["description"].split(",") can_id_write_array = keycloak_roles[1]["description"].split( ",") else: can_id_read_array = keycloak_roles[1]["description"].split(",") can_id_write_array = keycloak_roles[0]["description"].split( ",") roles = json.loads('{"can_id_read": "", "can_id_write" : ""}') roles["can_id_read"] = can_id_read_array roles["can_id_write"] = can_id_write_array except JSONDecodeError as error: print( "Json decoding error occurred. Input is not in json format or does not contain the required fields" ) raise SyntaxError except Exception as exp: print("An exception occurred while retrieving client roles {}". format(exp)) return roles
self.status_code = status_code KEYCLOAK_HOST = getenv("KEYCLOAK_HOST", "http://localhost:8080/auth/") KEYCLOAK_REALM = getenv("KEYCLOAK_REALM", "master") print(f"Waiting for Keycloak {KEYCLOAK_HOST} using realm '{KEYCLOAK_REALM}'.", end='') wait_for_http_connection_to(KEYCLOAK_HOST) try: keycloak_openid = KeycloakOpenID(server_url=KEYCLOAK_HOST, realm_name=KEYCLOAK_REALM, client_id="admin") KEYCLOAK_WELL_KNOW = keycloak_openid.well_know() KEYCLOAK_CERTS = keycloak_openid.certs() oAuthBearer = OAuth2AuthorizationCodeBearer( authorizationUrl=KEYCLOAK_WELL_KNOW['authorization_endpoint'], tokenUrl=KEYCLOAK_WELL_KNOW['token_endpoint']) except Exception as e: print(f"...failed: {e}. Endpoints with Authorization will not work.") def oAuthBearer(): raise AuthError("Keycloak not set up correctly!", 500) async def parse_bearer_token(security_scopes: SecurityScopes, token: str = Depends(oAuthBearer)): try:
from flask import request from flask_restful import Resource, Api import random import urllib.request import json import python_jwt as jwt, jwcrypto.jwk as jwk import datetime from keycloak import KeycloakOpenID app = Flask(__name__) api = Api(app) keycloak_openid = KeycloakOpenID(server_url="http://localhost:8180/auth/", client_id="poc-front-end", realm_name="master") certs = keycloak_openid.certs() print('certs={}'.format(certs)) KEYCLOAK_PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----\n' + keycloak_openid.public_key( ) + '\n-----END PUBLIC KEY-----' print('KEYCLOAK_PUBLIC_KEY={}'.format(KEYCLOAK_PUBLIC_KEY)) FORTUNES = [ { 'text': 'There are no manifestos like cannon and musketry.', 'author': 'The Duke of Wellington' }, { 'text': '"The fundamental principle of science, the definition almost, is this: the sole test of the validity of any idea is experiment."', 'author': 'Richard P. Feynman' },