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.

454 lines
15 KiB

6 years ago
6 years ago
6 years ago
  1. # -*- coding: utf-8 -*-
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (C) 2017 Marcos Pereira <marcospereira.mpj@gmail.com>
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy of
  8. # this software and associated documentation files (the "Software"), to deal in
  9. # the Software without restriction, including without limitation the rights to
  10. # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  11. # the Software, and to permit persons to whom the Software is furnished to do so,
  12. # subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in all
  15. # copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  19. # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  20. # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  21. # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  22. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. import json
  24. from jose import jwt
  25. from .authorization import Authorization
  26. from .connection import ConnectionManager
  27. from .exceptions import (
  28. KeycloakAuthorizationConfigError,
  29. KeycloakDeprecationError,
  30. KeycloakGetError,
  31. KeycloakInvalidTokenError,
  32. KeycloakRPTNotFound,
  33. raise_error_from_response,
  34. )
  35. from .urls_patterns import (
  36. URL_AUTH,
  37. URL_CERTS,
  38. URL_ENTITLEMENT,
  39. URL_INTROSPECT,
  40. URL_LOGOUT,
  41. URL_REALM,
  42. URL_TOKEN,
  43. URL_USERINFO,
  44. URL_WELL_KNOWN,
  45. )
  46. class KeycloakOpenID:
  47. """
  48. Keycloak OpenID client.
  49. :param server_url: Keycloak server url
  50. :param client_id: client id
  51. :param realm_name: realm name
  52. :param client_secret_key: client secret key
  53. :param verify: True if want check connection SSL
  54. :param custom_headers: dict of custom header to pass to each HTML request
  55. :param proxies: dict of proxies to sent the request by.
  56. """
  57. def __init__(
  58. self,
  59. server_url,
  60. realm_name,
  61. client_id,
  62. client_secret_key=None,
  63. verify=True,
  64. custom_headers=None,
  65. proxies=None,
  66. ):
  67. self.client_id = client_id
  68. self.client_secret_key = client_secret_key
  69. self.realm_name = realm_name
  70. headers = custom_headers if custom_headers is not None else dict()
  71. self.connection = ConnectionManager(
  72. base_url=server_url, headers=headers, timeout=60, verify=verify, proxies=proxies
  73. )
  74. self.authorization = Authorization()
  75. @property
  76. def client_id(self):
  77. return self._client_id
  78. @client_id.setter
  79. def client_id(self, value):
  80. self._client_id = value
  81. @property
  82. def client_secret_key(self):
  83. return self._client_secret_key
  84. @client_secret_key.setter
  85. def client_secret_key(self, value):
  86. self._client_secret_key = value
  87. @property
  88. def realm_name(self):
  89. return self._realm_name
  90. @realm_name.setter
  91. def realm_name(self, value):
  92. self._realm_name = value
  93. @property
  94. def connection(self):
  95. return self._connection
  96. @connection.setter
  97. def connection(self, value):
  98. self._connection = value
  99. @property
  100. def authorization(self):
  101. return self._authorization
  102. @authorization.setter
  103. def authorization(self, value):
  104. self._authorization = value
  105. def _add_secret_key(self, payload):
  106. """
  107. Add secret key if exist.
  108. :param payload:
  109. :return:
  110. """
  111. if self.client_secret_key:
  112. payload.update({"client_secret": self.client_secret_key})
  113. return payload
  114. def _build_name_role(self, role):
  115. """
  116. :param role:
  117. :return:
  118. """
  119. return self.client_id + "/" + role
  120. def _token_info(self, token, method_token_info, **kwargs):
  121. """
  122. :param token:
  123. :param method_token_info:
  124. :param kwargs:
  125. :return:
  126. """
  127. if method_token_info == "introspect":
  128. token_info = self.introspect(token)
  129. else:
  130. token_info = self.decode_token(token, **kwargs)
  131. return token_info
  132. def well_know(self):
  133. """The most important endpoint to understand is the well-known configuration
  134. endpoint. It lists endpoints and other configuration options relevant to
  135. the OpenID Connect implementation in Keycloak.
  136. :return It lists endpoints and other configuration options relevant.
  137. """
  138. params_path = {"realm-name": self.realm_name}
  139. data_raw = self.connection.raw_get(URL_WELL_KNOWN.format(**params_path))
  140. return raise_error_from_response(data_raw, KeycloakGetError)
  141. def auth_url(self, redirect_uri):
  142. """
  143. http://openid.net/specs/openid-connect-core-1_0.html#AuthorizationEndpoint
  144. :return:
  145. """
  146. params_path = {
  147. "authorization-endpoint": self.well_know()["authorization_endpoint"],
  148. "client-id": self.client_id,
  149. "redirect-uri": redirect_uri,
  150. }
  151. return URL_AUTH.format(**params_path)
  152. def token(
  153. self,
  154. username="",
  155. password="",
  156. grant_type=["password"],
  157. code="",
  158. redirect_uri="",
  159. totp=None,
  160. **extra
  161. ):
  162. """
  163. The token endpoint is used to obtain tokens. Tokens can either be obtained by
  164. exchanging an authorization code or by supplying credentials directly depending on
  165. what flow is used. The token endpoint is also used to obtain new access tokens
  166. when they expire.
  167. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  168. :param username:
  169. :param password:
  170. :param grant_type:
  171. :param code:
  172. :param redirect_uri:
  173. :param totp:
  174. :return:
  175. """
  176. params_path = {"realm-name": self.realm_name}
  177. payload = {
  178. "username": username,
  179. "password": password,
  180. "client_id": self.client_id,
  181. "grant_type": grant_type,
  182. "code": code,
  183. "redirect_uri": redirect_uri,
  184. }
  185. if extra:
  186. payload.update(extra)
  187. if totp:
  188. payload["totp"] = totp
  189. payload = self._add_secret_key(payload)
  190. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  191. return raise_error_from_response(data_raw, KeycloakGetError)
  192. def refresh_token(self, refresh_token, grant_type=["refresh_token"]):
  193. """
  194. The token endpoint is used to obtain tokens. Tokens can either be obtained by
  195. exchanging an authorization code or by supplying credentials directly depending on
  196. what flow is used. The token endpoint is also used to obtain new access tokens
  197. when they expire.
  198. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  199. :param refresh_token:
  200. :param grant_type:
  201. :return:
  202. """
  203. params_path = {"realm-name": self.realm_name}
  204. payload = {
  205. "client_id": self.client_id,
  206. "grant_type": grant_type,
  207. "refresh_token": refresh_token,
  208. }
  209. payload = self._add_secret_key(payload)
  210. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  211. return raise_error_from_response(data_raw, KeycloakGetError)
  212. def userinfo(self, token):
  213. """
  214. The userinfo endpoint returns standard claims about the authenticated user,
  215. and is protected by a bearer token.
  216. http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
  217. :param token:
  218. :return:
  219. """
  220. self.connection.add_param_headers("Authorization", "Bearer " + token)
  221. params_path = {"realm-name": self.realm_name}
  222. data_raw = self.connection.raw_get(URL_USERINFO.format(**params_path))
  223. return raise_error_from_response(data_raw, KeycloakGetError)
  224. def logout(self, refresh_token):
  225. """
  226. The logout endpoint logs out the authenticated user.
  227. :param refresh_token:
  228. :return:
  229. """
  230. params_path = {"realm-name": self.realm_name}
  231. payload = {"client_id": self.client_id, "refresh_token": refresh_token}
  232. payload = self._add_secret_key(payload)
  233. data_raw = self.connection.raw_post(URL_LOGOUT.format(**params_path), data=payload)
  234. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  235. def certs(self):
  236. """
  237. The certificate endpoint returns the public keys enabled by the realm, encoded as a
  238. JSON Web Key (JWK). Depending on the realm settings there can be one or more keys enabled
  239. for verifying tokens.
  240. https://tools.ietf.org/html/rfc7517
  241. :return:
  242. """
  243. params_path = {"realm-name": self.realm_name}
  244. data_raw = self.connection.raw_get(URL_CERTS.format(**params_path))
  245. return raise_error_from_response(data_raw, KeycloakGetError)
  246. def public_key(self):
  247. """
  248. The public key is exposed by the realm page directly.
  249. :return:
  250. """
  251. params_path = {"realm-name": self.realm_name}
  252. data_raw = self.connection.raw_get(URL_REALM.format(**params_path))
  253. return raise_error_from_response(data_raw, KeycloakGetError)["public_key"]
  254. def entitlement(self, token, resource_server_id):
  255. """
  256. Client applications can use a specific endpoint to obtain a special security token
  257. called a requesting party token (RPT). This token consists of all the entitlements
  258. (or permissions) for a user as a result of the evaluation of the permissions and
  259. authorization policies associated with the resources being requested. With an RPT,
  260. client applications can gain access to protected resources at the resource server.
  261. :return:
  262. """
  263. self.connection.add_param_headers("Authorization", "Bearer " + token)
  264. params_path = {"realm-name": self.realm_name, "resource-server-id": resource_server_id}
  265. data_raw = self.connection.raw_get(URL_ENTITLEMENT.format(**params_path))
  266. if data_raw.status_code == 404:
  267. return raise_error_from_response(data_raw, KeycloakDeprecationError)
  268. return raise_error_from_response(data_raw, KeycloakGetError)
  269. def introspect(self, token, rpt=None, token_type_hint=None):
  270. """
  271. The introspection endpoint is used to retrieve the active state of a token.
  272. It is can only be invoked by confidential clients.
  273. https://tools.ietf.org/html/rfc7662
  274. :param token:
  275. :param rpt:
  276. :param token_type_hint:
  277. :return:
  278. """
  279. params_path = {"realm-name": self.realm_name}
  280. payload = {"client_id": self.client_id, "token": token}
  281. if token_type_hint == "requesting_party_token":
  282. if rpt:
  283. payload.update({"token": rpt, "token_type_hint": token_type_hint})
  284. self.connection.add_param_headers("Authorization", "Bearer " + token)
  285. else:
  286. raise KeycloakRPTNotFound("Can't found RPT.")
  287. payload = self._add_secret_key(payload)
  288. data_raw = self.connection.raw_post(URL_INTROSPECT.format(**params_path), data=payload)
  289. return raise_error_from_response(data_raw, KeycloakGetError)
  290. def decode_token(self, token, key, algorithms=["RS256"], **kwargs):
  291. """
  292. A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data
  293. structure that represents a cryptographic key. This specification
  294. also defines a JWK Set JSON data structure that represents a set of
  295. JWKs. Cryptographic algorithms and identifiers for use with this
  296. specification are described in the separate JSON Web Algorithms (JWA)
  297. specification and IANA registries established by that specification.
  298. https://tools.ietf.org/html/rfc7517
  299. :param token:
  300. :param key:
  301. :param algorithms:
  302. :return:
  303. """
  304. return jwt.decode(token, key, algorithms=algorithms, audience=self.client_id, **kwargs)
  305. def load_authorization_config(self, path):
  306. """
  307. Load Keycloak settings (authorization)
  308. :param path: settings file (json)
  309. :return:
  310. """
  311. authorization_file = open(path, "r")
  312. authorization_json = json.loads(authorization_file.read())
  313. self.authorization.load_config(authorization_json)
  314. authorization_file.close()
  315. def get_policies(self, token, method_token_info="introspect", **kwargs):
  316. """
  317. Get policies by user token
  318. :param token: user token
  319. :return: policies list
  320. """
  321. if not self.authorization.policies:
  322. raise KeycloakAuthorizationConfigError(
  323. "Keycloak settings not found. Load Authorization Keycloak settings."
  324. )
  325. token_info = self._token_info(token, method_token_info, **kwargs)
  326. if method_token_info == "introspect" and not token_info["active"]:
  327. raise KeycloakInvalidTokenError("Token expired or invalid.")
  328. user_resources = token_info["resource_access"].get(self.client_id)
  329. if not user_resources:
  330. return None
  331. policies = []
  332. for policy_name, policy in self.authorization.policies.items():
  333. for role in user_resources["roles"]:
  334. if self._build_name_role(role) in policy.roles:
  335. policies.append(policy)
  336. return list(set(policies))
  337. def get_permissions(self, token, method_token_info="introspect", **kwargs):
  338. """
  339. Get permission by user token
  340. :param token: user token
  341. :param method_token_info: Decode token method
  342. :param kwargs: parameters for decode
  343. :return: permissions list
  344. """
  345. if not self.authorization.policies:
  346. raise KeycloakAuthorizationConfigError(
  347. "Keycloak settings not found. Load Authorization Keycloak settings."
  348. )
  349. token_info = self._token_info(token, method_token_info, **kwargs)
  350. if method_token_info == "introspect" and not token_info["active"]:
  351. raise KeycloakInvalidTokenError("Token expired or invalid.")
  352. user_resources = token_info["resource_access"].get(self.client_id)
  353. if not user_resources:
  354. return None
  355. permissions = []
  356. for policy_name, policy in self.authorization.policies.items():
  357. for role in user_resources["roles"]:
  358. if self._build_name_role(role) in policy.roles:
  359. permissions += policy.permissions
  360. return list(set(permissions))