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.

428 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. 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. return raise_error_from_response(data_raw, KeycloakGetError)
  237. def introspect(self, token, rpt=None, token_type_hint=None):
  238. """
  239. The introspection endpoint is used to retrieve the active state of a token. It is can only be
  240. invoked by confidential clients.
  241. https://tools.ietf.org/html/rfc7662
  242. :param token:
  243. :param rpt:
  244. :param token_type_hint:
  245. :return:
  246. """
  247. params_path = {"realm-name": self.realm_name}
  248. payload = {"client_id": self.client_id, "token": token}
  249. if token_type_hint == 'requesting_party_token':
  250. if rpt:
  251. payload.update({"token": rpt, "token_type_hint": token_type_hint})
  252. self.connection.add_param_headers("Authorization", "Bearer " + token)
  253. else:
  254. raise KeycloakRPTNotFound("Can't found RPT.")
  255. payload = self._add_secret_key(payload)
  256. data_raw = self.connection.raw_post(URL_INTROSPECT.format(**params_path),
  257. data=payload)
  258. return raise_error_from_response(data_raw, KeycloakGetError)
  259. def decode_token(self, token, key, algorithms=['RS256'], **kwargs):
  260. """
  261. A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data
  262. structure that represents a cryptographic key. This specification
  263. also defines a JWK Set JSON data structure that represents a set of
  264. JWKs. Cryptographic algorithms and identifiers for use with this
  265. specification are described in the separate JSON Web Algorithms (JWA)
  266. specification and IANA registries established by that specification.
  267. https://tools.ietf.org/html/rfc7517
  268. :param token:
  269. :param key:
  270. :param algorithms:
  271. :return:
  272. """
  273. return jwt.decode(token, key, algorithms=algorithms,
  274. audience=self.client_id, **kwargs)
  275. def load_authorization_config(self, path):
  276. """
  277. Load Keycloak settings (authorization)
  278. :param path: settings file (json)
  279. :return:
  280. """
  281. authorization_file = open(path, 'r')
  282. authorization_json = json.loads(authorization_file.read())
  283. self.authorization.load_config(authorization_json)
  284. authorization_file.close()
  285. def get_policies(self, token, method_token_info='introspect', **kwargs):
  286. """
  287. Get policies by user token
  288. :param token: user token
  289. :return: policies list
  290. """
  291. if not self.authorization.policies:
  292. raise KeycloakAuthorizationConfigError(
  293. "Keycloak settings not found. Load Authorization Keycloak settings."
  294. )
  295. token_info = self._token_info(token, method_token_info, **kwargs)
  296. if method_token_info == 'introspect' and not token_info['active']:
  297. raise KeycloakInvalidTokenError(
  298. "Token expired or invalid."
  299. )
  300. user_resources = token_info['resource_access'].get(self.client_id)
  301. if not user_resources:
  302. return None
  303. policies = []
  304. for policy_name, policy in self.authorization.policies.items():
  305. for role in user_resources['roles']:
  306. if self._build_name_role(role) in policy.roles:
  307. policies.append(policy)
  308. return list(set(policies))
  309. def get_permissions(self, token, method_token_info='introspect', **kwargs):
  310. """
  311. Get permission by user token
  312. :param token: user token
  313. :param method_token_info: Decode token method
  314. :param kwargs: parameters for decode
  315. :return: permissions list
  316. """
  317. if not self.authorization.policies:
  318. raise KeycloakAuthorizationConfigError(
  319. "Keycloak settings not found. Load Authorization Keycloak settings."
  320. )
  321. token_info = self._token_info(token, method_token_info, **kwargs)
  322. if method_token_info == 'introspect' and not token_info['active']:
  323. raise KeycloakInvalidTokenError(
  324. "Token expired or invalid."
  325. )
  326. user_resources = token_info['resource_access'].get(self.client_id)
  327. if not user_resources:
  328. return None
  329. permissions = []
  330. for policy_name, policy in self.authorization.policies.items():
  331. for role in user_resources['roles']:
  332. if self._build_name_role(role) in policy.roles:
  333. permissions += policy.permissions
  334. return list(set(permissions))