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.

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