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.

455 lines
15 KiB

6 years ago
6 years ago
6 years ago
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. def __init__(
  48. self,
  49. server_url,
  50. realm_name,
  51. client_id,
  52. client_secret_key=None,
  53. verify=True,
  54. custom_headers=None,
  55. proxies=None,
  56. ):
  57. """
  58. :param server_url: Keycloak server url
  59. :param client_id: client id
  60. :param realm_name: realm name
  61. :param client_secret_key: client secret key
  62. :param verify: True if want check connection SSL
  63. :param custom_headers: dict of custom header to pass to each HTML request
  64. :param proxies: dict of proxies to sent the request by.
  65. """
  66. self._client_id = client_id
  67. self._client_secret_key = client_secret_key
  68. self._realm_name = realm_name
  69. headers = dict()
  70. if custom_headers is not None:
  71. # merge custom headers to main headers
  72. headers.update(custom_headers)
  73. self._connection = ConnectionManager(
  74. base_url=server_url, headers=headers, timeout=60, verify=verify, proxies=proxies
  75. )
  76. self._authorization = Authorization()
  77. @property
  78. def client_id(self):
  79. return self._client_id
  80. @client_id.setter
  81. def client_id(self, value):
  82. self._client_id = value
  83. @property
  84. def client_secret_key(self):
  85. return self._client_secret_key
  86. @client_secret_key.setter
  87. def client_secret_key(self, value):
  88. self._client_secret_key = value
  89. @property
  90. def realm_name(self):
  91. return self._realm_name
  92. @realm_name.setter
  93. def realm_name(self, value):
  94. self._realm_name = value
  95. @property
  96. def connection(self):
  97. return self._connection
  98. @connection.setter
  99. def connection(self, value):
  100. self._connection = value
  101. @property
  102. def authorization(self):
  103. return self._authorization
  104. @authorization.setter
  105. def authorization(self, value):
  106. self._authorization = value
  107. def _add_secret_key(self, payload):
  108. """
  109. Add secret key if exist.
  110. :param payload:
  111. :return:
  112. """
  113. if self.client_secret_key:
  114. payload.update({"client_secret": self.client_secret_key})
  115. return payload
  116. def _build_name_role(self, role):
  117. """
  118. :param role:
  119. :return:
  120. """
  121. return self.client_id + "/" + role
  122. def _token_info(self, token, method_token_info, **kwargs):
  123. """
  124. :param token:
  125. :param method_token_info:
  126. :param kwargs:
  127. :return:
  128. """
  129. if method_token_info == "introspect":
  130. token_info = self.introspect(token)
  131. else:
  132. token_info = self.decode_token(token, **kwargs)
  133. return token_info
  134. def well_know(self):
  135. """The most important endpoint to understand is the well-known configuration
  136. endpoint. It lists endpoints and other configuration options relevant to
  137. the OpenID Connect implementation in Keycloak.
  138. :return It lists endpoints and other configuration options relevant.
  139. """
  140. params_path = {"realm-name": self.realm_name}
  141. data_raw = self.connection.raw_get(URL_WELL_KNOWN.format(**params_path))
  142. return raise_error_from_response(data_raw, KeycloakGetError)
  143. def auth_url(self, redirect_uri):
  144. """
  145. http://openid.net/specs/openid-connect-core-1_0.html#AuthorizationEndpoint
  146. :return:
  147. """
  148. params_path = {
  149. "authorization-endpoint": self.well_know()["authorization_endpoint"],
  150. "client-id": self.client_id,
  151. "redirect-uri": redirect_uri,
  152. }
  153. return URL_AUTH.format(**params_path)
  154. def token(
  155. self,
  156. username="",
  157. password="",
  158. grant_type=["password"],
  159. code="",
  160. redirect_uri="",
  161. totp=None,
  162. **extra
  163. ):
  164. """
  165. The token endpoint is used to obtain tokens. Tokens can either be obtained by
  166. exchanging an authorization code or by supplying credentials directly depending on
  167. what flow is used. The token endpoint is also used to obtain new access tokens
  168. when they expire.
  169. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  170. :param username:
  171. :param password:
  172. :param grant_type:
  173. :param code:
  174. :param redirect_uri
  175. :param totp
  176. :return:
  177. """
  178. params_path = {"realm-name": self.realm_name}
  179. payload = {
  180. "username": username,
  181. "password": password,
  182. "client_id": self.client_id,
  183. "grant_type": grant_type,
  184. "code": code,
  185. "redirect_uri": redirect_uri,
  186. }
  187. if extra:
  188. payload.update(extra)
  189. if totp:
  190. payload["totp"] = totp
  191. payload = self._add_secret_key(payload)
  192. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  193. return raise_error_from_response(data_raw, KeycloakGetError)
  194. def refresh_token(self, refresh_token, grant_type=["refresh_token"]):
  195. """
  196. The token endpoint is used to obtain tokens. Tokens can either be obtained by
  197. exchanging an authorization code or by supplying credentials directly depending on
  198. what flow is used. The token endpoint is also used to obtain new access tokens
  199. when they expire.
  200. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  201. :param refresh_token:
  202. :param grant_type:
  203. :return:
  204. """
  205. params_path = {"realm-name": self.realm_name}
  206. payload = {
  207. "client_id": self.client_id,
  208. "grant_type": grant_type,
  209. "refresh_token": refresh_token,
  210. }
  211. payload = self._add_secret_key(payload)
  212. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  213. return raise_error_from_response(data_raw, KeycloakGetError)
  214. def userinfo(self, token):
  215. """
  216. The userinfo endpoint returns standard claims about the authenticated user,
  217. and is protected by a bearer token.
  218. http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
  219. :param token:
  220. :return:
  221. """
  222. self.connection.add_param_headers("Authorization", "Bearer " + token)
  223. params_path = {"realm-name": self.realm_name}
  224. data_raw = self.connection.raw_get(URL_USERINFO.format(**params_path))
  225. return raise_error_from_response(data_raw, KeycloakGetError)
  226. def logout(self, refresh_token):
  227. """
  228. The logout endpoint logs out the authenticated user.
  229. :param refresh_token:
  230. :return:
  231. """
  232. params_path = {"realm-name": self.realm_name}
  233. payload = {"client_id": self.client_id, "refresh_token": refresh_token}
  234. payload = self._add_secret_key(payload)
  235. data_raw = self.connection.raw_post(URL_LOGOUT.format(**params_path), data=payload)
  236. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  237. def certs(self):
  238. """
  239. The certificate endpoint returns the public keys enabled by the realm, encoded as a
  240. JSON Web Key (JWK). Depending on the realm settings there can be one or more keys enabled
  241. for verifying tokens.
  242. https://tools.ietf.org/html/rfc7517
  243. :return:
  244. """
  245. params_path = {"realm-name": self.realm_name}
  246. data_raw = self.connection.raw_get(URL_CERTS.format(**params_path))
  247. return raise_error_from_response(data_raw, KeycloakGetError)
  248. def public_key(self):
  249. """
  250. The public key is exposed by the realm page directly.
  251. :return:
  252. """
  253. params_path = {"realm-name": self.realm_name}
  254. data_raw = self.connection.raw_get(URL_REALM.format(**params_path))
  255. return raise_error_from_response(data_raw, KeycloakGetError)["public_key"]
  256. def entitlement(self, token, resource_server_id):
  257. """
  258. Client applications can use a specific endpoint to obtain a special security token
  259. called a requesting party token (RPT). This token consists of all the entitlements
  260. (or permissions) for a user as a result of the evaluation of the permissions and authorization
  261. policies associated with the resources being requested. With an RPT, client applications can
  262. gain access to protected resources at the resource server.
  263. :return:
  264. """
  265. self.connection.add_param_headers("Authorization", "Bearer " + token)
  266. params_path = {"realm-name": self.realm_name, "resource-server-id": resource_server_id}
  267. data_raw = self.connection.raw_get(URL_ENTITLEMENT.format(**params_path))
  268. if data_raw.status_code == 404:
  269. return raise_error_from_response(data_raw, KeycloakDeprecationError)
  270. return raise_error_from_response(data_raw, KeycloakGetError)
  271. def introspect(self, token, rpt=None, token_type_hint=None):
  272. """
  273. The introspection endpoint is used to retrieve the active state of a token. It is can only be
  274. invoked by confidential clients.
  275. https://tools.ietf.org/html/rfc7662
  276. :param token:
  277. :param rpt:
  278. :param token_type_hint:
  279. :return:
  280. """
  281. params_path = {"realm-name": self.realm_name}
  282. payload = {"client_id": self.client_id, "token": token}
  283. if token_type_hint == "requesting_party_token":
  284. if rpt:
  285. payload.update({"token": rpt, "token_type_hint": token_type_hint})
  286. self.connection.add_param_headers("Authorization", "Bearer " + token)
  287. else:
  288. raise KeycloakRPTNotFound("Can't found RPT.")
  289. payload = self._add_secret_key(payload)
  290. data_raw = self.connection.raw_post(URL_INTROSPECT.format(**params_path), data=payload)
  291. return raise_error_from_response(data_raw, KeycloakGetError)
  292. def decode_token(self, token, key, algorithms=["RS256"], **kwargs):
  293. """
  294. A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data
  295. structure that represents a cryptographic key. This specification
  296. also defines a JWK Set JSON data structure that represents a set of
  297. JWKs. Cryptographic algorithms and identifiers for use with this
  298. specification are described in the separate JSON Web Algorithms (JWA)
  299. specification and IANA registries established by that specification.
  300. https://tools.ietf.org/html/rfc7517
  301. :param token:
  302. :param key:
  303. :param algorithms:
  304. :return:
  305. """
  306. return jwt.decode(token, key, algorithms=algorithms, audience=self.client_id, **kwargs)
  307. def load_authorization_config(self, path):
  308. """
  309. Load Keycloak settings (authorization)
  310. :param path: settings file (json)
  311. :return:
  312. """
  313. authorization_file = open(path, "r")
  314. authorization_json = json.loads(authorization_file.read())
  315. self.authorization.load_config(authorization_json)
  316. authorization_file.close()
  317. def get_policies(self, token, method_token_info="introspect", **kwargs):
  318. """
  319. Get policies by user token
  320. :param token: user token
  321. :return: policies list
  322. """
  323. if not self.authorization.policies:
  324. raise KeycloakAuthorizationConfigError(
  325. "Keycloak settings not found. Load Authorization Keycloak settings."
  326. )
  327. token_info = self._token_info(token, method_token_info, **kwargs)
  328. if method_token_info == "introspect" and not token_info["active"]:
  329. raise KeycloakInvalidTokenError("Token expired or invalid.")
  330. user_resources = token_info["resource_access"].get(self.client_id)
  331. if not user_resources:
  332. return None
  333. policies = []
  334. for policy_name, policy in self.authorization.policies.items():
  335. for role in user_resources["roles"]:
  336. if self._build_name_role(role) in policy.roles:
  337. policies.append(policy)
  338. return list(set(policies))
  339. def get_permissions(self, token, method_token_info="introspect", **kwargs):
  340. """
  341. Get permission by user token
  342. :param token: user token
  343. :param method_token_info: Decode token method
  344. :param kwargs: parameters for decode
  345. :return: permissions list
  346. """
  347. if not self.authorization.policies:
  348. raise KeycloakAuthorizationConfigError(
  349. "Keycloak settings not found. Load Authorization Keycloak settings."
  350. )
  351. token_info = self._token_info(token, method_token_info, **kwargs)
  352. if method_token_info == "introspect" and not token_info["active"]:
  353. raise KeycloakInvalidTokenError("Token expired or invalid.")
  354. user_resources = token_info["resource_access"].get(self.client_id)
  355. if not user_resources:
  356. return None
  357. permissions = []
  358. for policy_name, policy in self.authorization.policies.items():
  359. for role in user_resources["roles"]:
  360. if self._build_name_role(role) in policy.roles:
  361. permissions += policy.permissions
  362. return list(set(permissions))