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.

212 lines
8.0 KiB

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