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.

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