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.

310 lines
10 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, KeycloakInvalidTokenError
  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 _build_name_role(self, role):
  83. return self.client_id + "/" + role
  84. def well_know(self):
  85. """ The most important endpoint to understand is the well-known configuration
  86. endpoint. It lists endpoints and other configuration options relevant to
  87. the OpenID Connect implementation in Keycloak.
  88. :return It lists endpoints and other configuration options relevant.
  89. """
  90. params_path = {"realm-name": self.realm_name}
  91. data_raw = self.connection.raw_get(URL_WELL_KNOWN.format(**params_path))
  92. return raise_error_from_response(data_raw, KeycloakGetError)
  93. def auth_url(self, redirect_uri):
  94. """
  95. http://openid.net/specs/openid-connect-core-1_0.html#AuthorizationEndpoint
  96. :return:
  97. """
  98. return NotImplemented
  99. def token(self, username, password, grant_type=["password"]):
  100. """
  101. The token endpoint is used to obtain tokens. Tokens can either be obtained by
  102. exchanging an authorization code or by supplying credentials directly depending on
  103. what flow is used. The token endpoint is also used to obtain new access tokens
  104. when they expire.
  105. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  106. :param username:
  107. :param password:
  108. :param grant_type:
  109. :return:
  110. """
  111. params_path = {"realm-name": self.realm_name}
  112. payload = {"username": username, "password": password,
  113. "client_id": self.client_id, "grant_type": grant_type}
  114. payload = self._add_secret_key(payload)
  115. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path),
  116. data=payload)
  117. return raise_error_from_response(data_raw, KeycloakGetError)
  118. def userinfo(self, token):
  119. """
  120. The userinfo endpoint returns standard claims about the authenticated user,
  121. and is protected by a bearer token.
  122. http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
  123. :param token:
  124. :return:
  125. """
  126. self.connection.add_param_headers("Authorization", "Bearer " + token)
  127. params_path = {"realm-name": self.realm_name}
  128. data_raw = self.connection.raw_get(URL_USERINFO.format(**params_path))
  129. return raise_error_from_response(data_raw, KeycloakGetError)
  130. def logout(self, refresh_token):
  131. """
  132. The logout endpoint logs out the authenticated user.
  133. :param refresh_token:
  134. :return:
  135. """
  136. params_path = {"realm-name": self.realm_name}
  137. payload = {"client_id": self.client_id, "refresh_token": refresh_token}
  138. payload = self._add_secret_key(payload)
  139. data_raw = self.connection.raw_post(URL_LOGOUT.format(**params_path),
  140. data=payload)
  141. return raise_error_from_response(data_raw, KeycloakGetError, expected_code=204)
  142. def certs(self):
  143. """
  144. The certificate endpoint returns the public keys enabled by the realm, encoded as a
  145. JSON Web Key (JWK). Depending on the realm settings there can be one or more keys enabled
  146. for verifying tokens.
  147. https://tools.ietf.org/html/rfc7517
  148. :return:
  149. """
  150. params_path = {"realm-name": self.realm_name}
  151. data_raw = self.connection.raw_get(URL_CERTS.format(**params_path))
  152. return raise_error_from_response(data_raw, KeycloakGetError)
  153. def entitlement(self, token, resource_server_id):
  154. """
  155. Client applications can use a specific endpoint to obtain a special security token
  156. called a requesting party token (RPT). This token consists of all the entitlements
  157. (or permissions) for a user as a result of the evaluation of the permissions and authorization
  158. policies associated with the resources being requested. With an RPT, client applications can
  159. gain access to protected resources at the resource server.
  160. :return:
  161. """
  162. self.connection.add_param_headers("Authorization", "Bearer " + token)
  163. params_path = {"realm-name": self.realm_name, "resource-server-id": resource_server_id}
  164. data_raw = self.connection.raw_get(URL_ENTITLEMENT.format(**params_path))
  165. return raise_error_from_response(data_raw, KeycloakGetError)
  166. def instropect(self, token, rpt=None, token_type_hint=None):
  167. """
  168. The introspection endpoint is used to retrieve the active state of a token. It is can only be
  169. invoked by confidential clients.
  170. https://tools.ietf.org/html/rfc7662
  171. :param token:
  172. :param rpt:
  173. :param token_type_hint:
  174. :return:
  175. """
  176. params_path = {"realm-name": self.realm_name}
  177. payload = {"client_id": self.client_id, "token": token}
  178. if token_type_hint == 'requesting_party_token':
  179. if rpt:
  180. payload.update({"token": rpt, "token_type_hint": token_type_hint})
  181. self.connection.add_param_headers("Authorization", "Bearer " + token)
  182. else:
  183. raise KeycloakRPTNotFound("Can't found RPT.")
  184. payload = self._add_secret_key(payload)
  185. data_raw = self.connection.raw_post(URL_INTROSPECT.format(**params_path),
  186. data=payload)
  187. return raise_error_from_response(data_raw, KeycloakGetError)
  188. def decode_token(self, token, key, algorithms=['RS256'], **kwargs):
  189. """
  190. A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data
  191. structure that represents a cryptographic key. This specification
  192. also defines a JWK Set JSON data structure that represents a set of
  193. JWKs. Cryptographic algorithms and identifiers for use with this
  194. specification are described in the separate JSON Web Algorithms (JWA)
  195. specification and IANA registries established by that specification.
  196. https://tools.ietf.org/html/rfc7517
  197. :param token:
  198. :param key:
  199. :param algorithms:
  200. :return:
  201. """
  202. return jwt.decode(token, key, algorithms=algorithms,
  203. audience=self.client_id, **kwargs)
  204. def load_authorization_config(self, path):
  205. """
  206. Load Keycloak settings (authorization)
  207. :param path: settings file (json)
  208. :return:
  209. """
  210. authorization_file = open(path, 'r')
  211. authorization_json = json.loads(authorization_file.read())
  212. self.authorization.load_config(authorization_json)
  213. authorization_file.close()
  214. def get_permissions(self, token):
  215. """
  216. Get permission by user token
  217. :param token: user token
  218. :return: permissions list
  219. """
  220. if not self.authorization.policies:
  221. raise KeycloakAuthorizationConfigError(
  222. "Keycloak settings not found. Load Authorization Keycloak settings."
  223. )
  224. token_info = self.instropect(token)
  225. if not token_info['active']:
  226. raise KeycloakInvalidTokenError(
  227. "Token expired or invalid."
  228. )
  229. user_resources = token_info['resource_access'].get(self.client_id)
  230. if not user_resources:
  231. return None
  232. permissions = []
  233. for policy_name, policy in self.authorization.policies.items():
  234. for role in user_resources['roles']:
  235. if self._build_name_role(role) in policy.roles:
  236. permissions += policy.permissions
  237. return list(set(permissions))