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.

400 lines
14 KiB

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