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.

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