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.

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