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.

390 lines
13 KiB

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