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.

409 lines
14 KiB

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