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.

365 lines
12 KiB

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