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.

231 lines
8.1 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 .exceptions import raise_error_from_response, KeycloakGetError, KeycloakSecretNotFound, \
  18. KeycloakRPTNotFound
  19. from .urls_patterns import (
  20. URL_AUTH,
  21. URL_TOKEN,
  22. URL_USERINFO,
  23. URL_WELL_KNOWN,
  24. URL_LOGOUT,
  25. URL_CERTS,
  26. URL_ENTITLEMENT,
  27. URL_INTROSPECT
  28. )
  29. from .connection import ConnectionManager
  30. from jose import jwt
  31. class Keycloak:
  32. def __init__(self, server_url, client_id, realm_name, client_secret_key=None):
  33. self.client_id = client_id
  34. self.client_secret_key = client_secret_key
  35. self.realm_name = realm_name
  36. self.connection = ConnectionManager(base_url=server_url,
  37. headers={},
  38. timeout=60)
  39. @property
  40. def get_client_id(self):
  41. return self.client_id
  42. @property
  43. def get_client_secret_key(self):
  44. return self.client_secret_key
  45. @property
  46. def get_realm_name(self):
  47. return self.realm_name
  48. @property
  49. def get_connection(self):
  50. return self.connection
  51. def _add_secret_key(self, payload):
  52. """
  53. Add secret key if exist.
  54. :param payload:
  55. :return:
  56. """
  57. if self.client_secret_key:
  58. payload.update({"client_secret": self.client_secret_key})
  59. return payload
  60. def well_know(self):
  61. """ The most important endpoint to understand is the well-known configuration
  62. endpoint. It lists endpoints and other configuration options relevant to
  63. the OpenID Connect implementation in Keycloak.
  64. :return It lists endpoints and other configuration options relevant.
  65. """
  66. params_path = {"realm-name": self.realm_name}
  67. data_raw = self.connection.raw_get(URL_WELL_KNOWN.format(**params_path))
  68. return raise_error_from_response(data_raw, KeycloakGetError)
  69. def auth_url(self, redirect_uri):
  70. """
  71. http://openid.net/specs/openid-connect-core-1_0.html#AuthorizationEndpoint
  72. :return:
  73. """
  74. return NotImplemented
  75. def token(self, username, password, grant_type=["password"]):
  76. """
  77. The token endpoint is used to obtain tokens. Tokens can either be obtained by
  78. exchanging an authorization code or by supplying credentials directly depending on
  79. what flow is used. The token endpoint is also used to obtain new access tokens
  80. when they expire.
  81. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  82. :param username:
  83. :param password:
  84. :param grant_type:
  85. :return:
  86. """
  87. params_path = {"realm-name": self.realm_name}
  88. payload = {"username": username, "password": password,
  89. "client_id": self.client_id, "grant_type": grant_type}
  90. payload = self._add_secret_key(payload)
  91. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path),
  92. data=payload)
  93. return raise_error_from_response(data_raw, KeycloakGetError)
  94. def userinfo(self, token):
  95. """
  96. The userinfo endpoint returns standard claims about the authenticated user,
  97. and is protected by a bearer token.
  98. http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
  99. :param token:
  100. :return:
  101. """
  102. self.connection.add_param_headers("Authorization", "Bearer " + token)
  103. params_path = {"realm-name": self.realm_name}
  104. data_raw = self.connection.raw_get(URL_USERINFO.format(**params_path))
  105. return raise_error_from_response(data_raw, KeycloakGetError)
  106. def logout(self, refresh_token):
  107. """
  108. The logout endpoint logs out the authenticated user.
  109. :param refresh_token:
  110. :return:
  111. """
  112. params_path = {"realm-name": self.realm_name}
  113. payload = {"client_id": self.client_id, "refresh_token": refresh_token}
  114. payload = self._add_secret_key(payload)
  115. data_raw = self.connection.raw_post(URL_LOGOUT.format(**params_path),
  116. data=payload)
  117. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  118. def certs(self):
  119. """
  120. The certificate endpoint returns the public keys enabled by the realm, encoded as a
  121. JSON Web Key (JWK). Depending on the realm settings there can be one or more keys enabled
  122. for verifying tokens.
  123. https://tools.ietf.org/html/rfc7517
  124. :return:
  125. """
  126. params_path = {"realm-name": self.realm_name}
  127. data_raw = self.connection.raw_get(URL_CERTS.format(**params_path))
  128. return raise_error_from_response(data_raw, KeycloakGetError)
  129. def entitlement(self, token, resource_server_id):
  130. """
  131. Client applications can use a specific endpoint to obtain a special security token
  132. called a requesting party token (RPT). This token consists of all the entitlements
  133. (or permissions) for a user as a result of the evaluation of the permissions and authorization
  134. policies associated with the resources being requested. With an RPT, client applications can
  135. gain access to protected resources at the resource server.
  136. :return:
  137. """
  138. self.connection.add_param_headers("Authorization", "Bearer " + token)
  139. params_path = {"realm-name": self.realm_name, "resource-server-id": resource_server_id}
  140. data_raw = self.connection.raw_get(URL_ENTITLEMENT.format(**params_path))
  141. return raise_error_from_response(data_raw, KeycloakGetError)
  142. def instropect(self, token, rpt=None, token_type_hint=None):
  143. """
  144. The introspection endpoint is used to retrieve the active state of a token. It is can only be
  145. invoked by confidential clients.
  146. https://tools.ietf.org/html/rfc7662
  147. :param token:
  148. :param rpt:
  149. :param token_type_hint:
  150. :return:
  151. """
  152. params_path = {"realm-name": self.realm_name}
  153. payload = {"client_id": self.client_id, "token": token}
  154. if token_type_hint == 'requesting_party_token':
  155. if rpt:
  156. payload.update({"token": rpt, "token_type_hint": token_type_hint})
  157. self.connection.add_param_headers("Authorization", "Bearer " + token)
  158. else:
  159. raise KeycloakRPTNotFound("Can't found RPT.")
  160. payload = self._add_secret_key(payload)
  161. data_raw = self.connection.raw_post(URL_INTROSPECT.format(**params_path),
  162. data=payload)
  163. return raise_error_from_response(data_raw, KeycloakGetError)
  164. def decode_token(self, token, key, algorithms=['RS256'], **kwargs):
  165. """
  166. A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data
  167. structure that represents a cryptographic key. This specification
  168. also defines a JWK Set JSON data structure that represents a set of
  169. JWKs. Cryptographic algorithms and identifiers for use with this
  170. specification are described in the separate JSON Web Algorithms (JWA)
  171. specification and IANA registries established by that specification.
  172. https://tools.ietf.org/html/rfc7517
  173. :param token:
  174. :param key:
  175. :param algorithms:
  176. :return:
  177. """
  178. return jwt.decode(token, key, algorithms=algorithms,
  179. audience=self.client_id, **kwargs)