You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

282 lines
9.4 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2017 Marcos Pereira <marcospereira.mpj@gmail.com>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Lesser General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Lesser General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Lesser General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. from keycloak.authorization import Authorization
  18. from keycloak.exceptions import KeycloakAuthorizationConfigError
  19. from .exceptions import raise_error_from_response, KeycloakGetError, KeycloakSecretNotFound, \
  20. KeycloakRPTNotFound
  21. from .urls_patterns import (
  22. URL_AUTH,
  23. URL_TOKEN,
  24. URL_USERINFO,
  25. URL_WELL_KNOWN,
  26. URL_LOGOUT,
  27. URL_CERTS,
  28. URL_ENTITLEMENT,
  29. URL_INTROSPECT
  30. )
  31. from .connection import ConnectionManager
  32. from jose import jwt
  33. import json
  34. class Keycloak:
  35. def __init__(self, server_url, client_id, realm_name, client_secret_key=None):
  36. self._client_id = client_id
  37. self._client_secret_key = client_secret_key
  38. self._realm_name = realm_name
  39. self._connection = ConnectionManager(base_url=server_url,
  40. headers={},
  41. timeout=60)
  42. self._authorization = Authorization()
  43. @property
  44. def client_id(self):
  45. return self._client_id
  46. @client_id.setter
  47. def client_id(self, value):
  48. self._client_id = value
  49. @property
  50. def client_secret_key(self):
  51. return self._client_secret_key
  52. @client_secret_key.setter
  53. def client_secret_key(self, value):
  54. self._client_secret_key = value
  55. @property
  56. def realm_name(self):
  57. return self._realm_name
  58. @realm_name.setter
  59. def realm_name(self, value):
  60. self._realm_name = value
  61. @property
  62. def connection(self):
  63. return self._connection
  64. @connection.setter
  65. def connection(self, value):
  66. self._connection = value
  67. @property
  68. def authorization(self):
  69. return self._authorization
  70. @authorization.setter
  71. def authorization(self, value):
  72. self._authorization = value
  73. def _add_secret_key(self, payload):
  74. """
  75. Add secret key if exist.
  76. :param payload:
  77. :return:
  78. """
  79. if self.client_secret_key:
  80. payload.update({"client_secret": self.client_secret_key})
  81. return payload
  82. def well_know(self):
  83. """ The most important endpoint to understand is the well-known configuration
  84. endpoint. It lists endpoints and other configuration options relevant to
  85. the OpenID Connect implementation in Keycloak.
  86. :return It lists endpoints and other configuration options relevant.
  87. """
  88. params_path = {"realm-name": self.realm_name}
  89. data_raw = self.connection.raw_get(URL_WELL_KNOWN.format(**params_path))
  90. return raise_error_from_response(data_raw, KeycloakGetError)
  91. def auth_url(self, redirect_uri):
  92. """
  93. http://openid.net/specs/openid-connect-core-1_0.html#AuthorizationEndpoint
  94. :return:
  95. """
  96. return NotImplemented
  97. def token(self, username, password, grant_type=["password"]):
  98. """
  99. The token endpoint is used to obtain tokens. Tokens can either be obtained by
  100. exchanging an authorization code or by supplying credentials directly depending on
  101. what flow is used. The token endpoint is also used to obtain new access tokens
  102. when they expire.
  103. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  104. :param username:
  105. :param password:
  106. :param grant_type:
  107. :return:
  108. """
  109. params_path = {"realm-name": self.realm_name}
  110. payload = {"username": username, "password": password,
  111. "client_id": self.client_id, "grant_type": grant_type}
  112. payload = self._add_secret_key(payload)
  113. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path),
  114. data=payload)
  115. return raise_error_from_response(data_raw, KeycloakGetError)
  116. def userinfo(self, token):
  117. """
  118. The userinfo endpoint returns standard claims about the authenticated user,
  119. and is protected by a bearer token.
  120. http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
  121. :param token:
  122. :return:
  123. """
  124. self.connection.add_param_headers("Authorization", "Bearer " + token)
  125. params_path = {"realm-name": self.realm_name}
  126. data_raw = self.connection.raw_get(URL_USERINFO.format(**params_path))
  127. return raise_error_from_response(data_raw, KeycloakGetError)
  128. def logout(self, refresh_token):
  129. """
  130. The logout endpoint logs out the authenticated user.
  131. :param refresh_token:
  132. :return:
  133. """
  134. params_path = {"realm-name": self.realm_name}
  135. payload = {"client_id": self.client_id, "refresh_token": refresh_token}
  136. payload = self._add_secret_key(payload)
  137. data_raw = self.connection.raw_post(URL_LOGOUT.format(**params_path),
  138. data=payload)
  139. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  140. def certs(self):
  141. """
  142. The certificate endpoint returns the public keys enabled by the realm, encoded as a
  143. JSON Web Key (JWK). Depending on the realm settings there can be one or more keys enabled
  144. for verifying tokens.
  145. https://tools.ietf.org/html/rfc7517
  146. :return:
  147. """
  148. params_path = {"realm-name": self.realm_name}
  149. data_raw = self.connection.raw_get(URL_CERTS.format(**params_path))
  150. return raise_error_from_response(data_raw, KeycloakGetError)
  151. def entitlement(self, token, resource_server_id):
  152. """
  153. Client applications can use a specific endpoint to obtain a special security token
  154. called a requesting party token (RPT). This token consists of all the entitlements
  155. (or permissions) for a user as a result of the evaluation of the permissions and authorization
  156. policies associated with the resources being requested. With an RPT, client applications can
  157. gain access to protected resources at the resource server.
  158. :return:
  159. """
  160. self.connection.add_param_headers("Authorization", "Bearer " + token)
  161. params_path = {"realm-name": self.realm_name, "resource-server-id": resource_server_id}
  162. data_raw = self.connection.raw_get(URL_ENTITLEMENT.format(**params_path))
  163. return raise_error_from_response(data_raw, KeycloakGetError)
  164. def instropect(self, token, rpt=None, token_type_hint=None):
  165. """
  166. The introspection endpoint is used to retrieve the active state of a token. It is can only be
  167. invoked by confidential clients.
  168. https://tools.ietf.org/html/rfc7662
  169. :param token:
  170. :param rpt:
  171. :param token_type_hint:
  172. :return:
  173. """
  174. params_path = {"realm-name": self.realm_name}
  175. payload = {"client_id": self.client_id, "token": token}
  176. if token_type_hint == 'requesting_party_token':
  177. if rpt:
  178. payload.update({"token": rpt, "token_type_hint": token_type_hint})
  179. self.connection.add_param_headers("Authorization", "Bearer " + token)
  180. else:
  181. raise KeycloakRPTNotFound("Can't found RPT.")
  182. payload = self._add_secret_key(payload)
  183. data_raw = self.connection.raw_post(URL_INTROSPECT.format(**params_path),
  184. data=payload)
  185. return raise_error_from_response(data_raw, KeycloakGetError)
  186. def decode_token(self, token, key, algorithms=['RS256'], **kwargs):
  187. """
  188. A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data
  189. structure that represents a cryptographic key. This specification
  190. also defines a JWK Set JSON data structure that represents a set of
  191. JWKs. Cryptographic algorithms and identifiers for use with this
  192. specification are described in the separate JSON Web Algorithms (JWA)
  193. specification and IANA registries established by that specification.
  194. https://tools.ietf.org/html/rfc7517
  195. :param token:
  196. :param key:
  197. :param algorithms:
  198. :return:
  199. """
  200. return jwt.decode(token, key, algorithms=algorithms,
  201. audience=self.client_id, **kwargs)
  202. def load_authorization_config(self, path):
  203. """
  204. Load Keycloak settings (authorization)
  205. :param path: settings file (json)
  206. :return:
  207. """
  208. authorization_file = open(path, 'r')
  209. authorization_json = json.loads(authorization_file.read())
  210. self.authorization.load_config(authorization_json)
  211. authorization_file.close()
  212. def get_permissions(self):
  213. if not self.authorization.policies:
  214. raise KeycloakAuthorizationConfigError(
  215. "Keycloak settings not found. Load Authorization Keycloak settings."
  216. )
  217. return