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.

362 lines
12 KiB

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