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.

433 lines
15 KiB

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