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.

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