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.

521 lines
17 KiB

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 (
  28. KeycloakAuthenticationError,
  29. KeycloakAuthorizationConfigError,
  30. KeycloakDeprecationError,
  31. KeycloakGetError,
  32. KeycloakInvalidTokenError,
  33. KeycloakPostError,
  34. KeycloakRPTNotFound,
  35. raise_error_from_response,
  36. )
  37. from .uma_permissions import AuthStatus, build_permission_param
  38. from .urls_patterns import (
  39. URL_AUTH,
  40. URL_CERTS,
  41. URL_ENTITLEMENT,
  42. URL_INTROSPECT,
  43. URL_LOGOUT,
  44. URL_REALM,
  45. URL_TOKEN,
  46. URL_USERINFO,
  47. URL_WELL_KNOWN,
  48. )
  49. class KeycloakOpenID:
  50. """
  51. Keycloak OpenID client.
  52. :param server_url: Keycloak server url
  53. :param client_id: client id
  54. :param realm_name: realm name
  55. :param client_secret_key: client secret key
  56. :param verify: True if want check connection SSL
  57. :param custom_headers: dict of custom header to pass to each HTML request
  58. :param proxies: dict of proxies to sent the request by.
  59. """
  60. def __init__(
  61. self,
  62. server_url,
  63. realm_name,
  64. client_id,
  65. client_secret_key=None,
  66. verify=True,
  67. custom_headers=None,
  68. proxies=None,
  69. ):
  70. self.client_id = client_id
  71. self.client_secret_key = client_secret_key
  72. self.realm_name = realm_name
  73. headers = custom_headers if custom_headers is not None else dict()
  74. self.connection = ConnectionManager(
  75. base_url=server_url, headers=headers, timeout=60, verify=verify, proxies=proxies
  76. )
  77. self.authorization = Authorization()
  78. @property
  79. def client_id(self):
  80. return self._client_id
  81. @client_id.setter
  82. def client_id(self, value):
  83. self._client_id = value
  84. @property
  85. def client_secret_key(self):
  86. return self._client_secret_key
  87. @client_secret_key.setter
  88. def client_secret_key(self, value):
  89. self._client_secret_key = value
  90. @property
  91. def realm_name(self):
  92. return self._realm_name
  93. @realm_name.setter
  94. def realm_name(self, value):
  95. self._realm_name = value
  96. @property
  97. def connection(self):
  98. return self._connection
  99. @connection.setter
  100. def connection(self, value):
  101. self._connection = value
  102. @property
  103. def authorization(self):
  104. return self._authorization
  105. @authorization.setter
  106. def authorization(self, value):
  107. self._authorization = value
  108. def _add_secret_key(self, payload):
  109. """
  110. Add secret key if exist.
  111. :param payload:
  112. :return:
  113. """
  114. if self.client_secret_key:
  115. payload.update({"client_secret": self.client_secret_key})
  116. return payload
  117. def _build_name_role(self, role):
  118. """
  119. :param role:
  120. :return:
  121. """
  122. return self.client_id + "/" + role
  123. def _token_info(self, token, method_token_info, **kwargs):
  124. """
  125. :param token:
  126. :param method_token_info:
  127. :param kwargs:
  128. :return:
  129. """
  130. if method_token_info == "introspect":
  131. token_info = self.introspect(token)
  132. else:
  133. token_info = self.decode_token(token, **kwargs)
  134. return token_info
  135. def well_known(self):
  136. """The most important endpoint to understand is the well-known configuration
  137. endpoint. It lists endpoints and other configuration options relevant to
  138. the OpenID Connect implementation in Keycloak.
  139. :return It lists endpoints and other configuration options relevant.
  140. """
  141. params_path = {"realm-name": self.realm_name}
  142. data_raw = self.connection.raw_get(URL_WELL_KNOWN.format(**params_path))
  143. return raise_error_from_response(data_raw, KeycloakGetError)
  144. def auth_url(self, redirect_uri):
  145. """
  146. http://openid.net/specs/openid-connect-core-1_0.html#AuthorizationEndpoint
  147. :return:
  148. """
  149. params_path = {
  150. "authorization-endpoint": self.well_known()["authorization_endpoint"],
  151. "client-id": self.client_id,
  152. "redirect-uri": redirect_uri,
  153. }
  154. return URL_AUTH.format(**params_path)
  155. def token(
  156. self,
  157. username="",
  158. password="",
  159. grant_type=["password"],
  160. code="",
  161. redirect_uri="",
  162. totp=None,
  163. **extra
  164. ):
  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 username:
  172. :param password:
  173. :param grant_type:
  174. :param code:
  175. :param redirect_uri:
  176. :param totp:
  177. :return:
  178. """
  179. params_path = {"realm-name": self.realm_name}
  180. payload = {
  181. "username": username,
  182. "password": password,
  183. "client_id": self.client_id,
  184. "grant_type": grant_type,
  185. "code": code,
  186. "redirect_uri": redirect_uri,
  187. }
  188. if extra:
  189. payload.update(extra)
  190. if totp:
  191. payload["totp"] = totp
  192. payload = self._add_secret_key(payload)
  193. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  194. return raise_error_from_response(data_raw, KeycloakGetError)
  195. def refresh_token(self, refresh_token, grant_type=["refresh_token"]):
  196. """
  197. The token endpoint is used to obtain tokens. Tokens can either be obtained by
  198. exchanging an authorization code or by supplying credentials directly depending on
  199. what flow is used. The token endpoint is also used to obtain new access tokens
  200. when they expire.
  201. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  202. :param refresh_token:
  203. :param grant_type:
  204. :return:
  205. """
  206. params_path = {"realm-name": self.realm_name}
  207. payload = {
  208. "client_id": self.client_id,
  209. "grant_type": grant_type,
  210. "refresh_token": refresh_token,
  211. }
  212. payload = self._add_secret_key(payload)
  213. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  214. return raise_error_from_response(data_raw, KeycloakGetError)
  215. def userinfo(self, token):
  216. """
  217. The userinfo endpoint returns standard claims about the authenticated user,
  218. and is protected by a bearer token.
  219. http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
  220. :param token:
  221. :return:
  222. """
  223. self.connection.add_param_headers("Authorization", "Bearer " + token)
  224. params_path = {"realm-name": self.realm_name}
  225. data_raw = self.connection.raw_get(URL_USERINFO.format(**params_path))
  226. return raise_error_from_response(data_raw, KeycloakGetError)
  227. def logout(self, refresh_token):
  228. """
  229. The logout endpoint logs out the authenticated user.
  230. :param refresh_token:
  231. :return:
  232. """
  233. params_path = {"realm-name": self.realm_name}
  234. payload = {"client_id": self.client_id, "refresh_token": refresh_token}
  235. payload = self._add_secret_key(payload)
  236. data_raw = self.connection.raw_post(URL_LOGOUT.format(**params_path), data=payload)
  237. return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
  238. def certs(self):
  239. """
  240. The certificate endpoint returns the public keys enabled by the realm, encoded as a
  241. JSON Web Key (JWK). Depending on the realm settings there can be one or more keys enabled
  242. for verifying tokens.
  243. https://tools.ietf.org/html/rfc7517
  244. :return:
  245. """
  246. params_path = {"realm-name": self.realm_name}
  247. data_raw = self.connection.raw_get(URL_CERTS.format(**params_path))
  248. return raise_error_from_response(data_raw, KeycloakGetError)
  249. def public_key(self):
  250. """
  251. The public key is exposed by the realm page directly.
  252. :return:
  253. """
  254. params_path = {"realm-name": self.realm_name}
  255. data_raw = self.connection.raw_get(URL_REALM.format(**params_path))
  256. return raise_error_from_response(data_raw, KeycloakGetError)["public_key"]
  257. def entitlement(self, token, resource_server_id):
  258. """
  259. Client applications can use a specific endpoint to obtain a special security token
  260. called a requesting party token (RPT). This token consists of all the entitlements
  261. (or permissions) for a user as a result of the evaluation of the permissions and
  262. authorization policies associated with the resources being requested. With an RPT,
  263. client applications can gain access to protected resources at the resource server.
  264. :return:
  265. """
  266. self.connection.add_param_headers("Authorization", "Bearer " + token)
  267. params_path = {"realm-name": self.realm_name, "resource-server-id": resource_server_id}
  268. data_raw = self.connection.raw_get(URL_ENTITLEMENT.format(**params_path))
  269. if data_raw.status_code == 404:
  270. return raise_error_from_response(data_raw, KeycloakDeprecationError)
  271. return raise_error_from_response(data_raw, KeycloakGetError)
  272. def introspect(self, token, rpt=None, token_type_hint=None):
  273. """
  274. The introspection endpoint is used to retrieve the active state of a token.
  275. It is can only be invoked by confidential clients.
  276. https://tools.ietf.org/html/rfc7662
  277. :param token:
  278. :param rpt:
  279. :param token_type_hint:
  280. :return:
  281. """
  282. params_path = {"realm-name": self.realm_name}
  283. payload = {"client_id": self.client_id, "token": token}
  284. if token_type_hint == "requesting_party_token":
  285. if rpt:
  286. payload.update({"token": rpt, "token_type_hint": token_type_hint})
  287. self.connection.add_param_headers("Authorization", "Bearer " + token)
  288. else:
  289. raise KeycloakRPTNotFound("Can't found RPT.")
  290. payload = self._add_secret_key(payload)
  291. data_raw = self.connection.raw_post(URL_INTROSPECT.format(**params_path), data=payload)
  292. return raise_error_from_response(data_raw, KeycloakGetError)
  293. def decode_token(self, token, key, algorithms=["RS256"], **kwargs):
  294. """
  295. A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data
  296. structure that represents a cryptographic key. This specification
  297. also defines a JWK Set JSON data structure that represents a set of
  298. JWKs. Cryptographic algorithms and identifiers for use with this
  299. specification are described in the separate JSON Web Algorithms (JWA)
  300. specification and IANA registries established by that specification.
  301. https://tools.ietf.org/html/rfc7517
  302. :param token:
  303. :param key:
  304. :param algorithms:
  305. :return:
  306. """
  307. return jwt.decode(token, key, algorithms=algorithms, audience=self.client_id, **kwargs)
  308. def load_authorization_config(self, path):
  309. """
  310. Load Keycloak settings (authorization)
  311. :param path: settings file (json)
  312. :return:
  313. """
  314. authorization_file = open(path, "r")
  315. authorization_json = json.loads(authorization_file.read())
  316. self.authorization.load_config(authorization_json)
  317. authorization_file.close()
  318. def get_policies(self, token, method_token_info="introspect", **kwargs):
  319. """
  320. Get policies by user token
  321. :param token: user token
  322. :return: policies list
  323. """
  324. if not self.authorization.policies:
  325. raise KeycloakAuthorizationConfigError(
  326. "Keycloak settings not found. Load Authorization Keycloak settings."
  327. )
  328. token_info = self._token_info(token, method_token_info, **kwargs)
  329. if method_token_info == "introspect" and not token_info["active"]:
  330. raise KeycloakInvalidTokenError("Token expired or invalid.")
  331. user_resources = token_info["resource_access"].get(self.client_id)
  332. if not user_resources:
  333. return None
  334. policies = []
  335. for policy_name, policy in self.authorization.policies.items():
  336. for role in user_resources["roles"]:
  337. if self._build_name_role(role) in policy.roles:
  338. policies.append(policy)
  339. return list(set(policies))
  340. def get_permissions(self, token, method_token_info="introspect", **kwargs):
  341. """
  342. Get permission by user token
  343. :param token: user token
  344. :param method_token_info: Decode token method
  345. :param kwargs: parameters for decode
  346. :return: permissions list
  347. """
  348. if not self.authorization.policies:
  349. raise KeycloakAuthorizationConfigError(
  350. "Keycloak settings not found. Load Authorization Keycloak settings."
  351. )
  352. token_info = self._token_info(token, method_token_info, **kwargs)
  353. if method_token_info == "introspect" and not token_info["active"]:
  354. raise KeycloakInvalidTokenError("Token expired or invalid.")
  355. user_resources = token_info["resource_access"].get(self.client_id)
  356. if not user_resources:
  357. return None
  358. permissions = []
  359. for policy_name, policy in self.authorization.policies.items():
  360. for role in user_resources["roles"]:
  361. if self._build_name_role(role) in policy.roles:
  362. permissions += policy.permissions
  363. return list(set(permissions))
  364. def uma_permissions(self, token, permissions=""):
  365. """
  366. Get UMA permissions by user token with requested permissions
  367. The token endpoint is used to retrieve UMA permissions from Keycloak. It can only be
  368. invoked by confidential clients.
  369. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  370. :param token: user token
  371. :param permissions: list of uma permissions list(resource:scope) requested by the user
  372. :return: permissions list
  373. """
  374. permission = build_permission_param(permissions)
  375. params_path = {"realm-name": self.realm_name}
  376. payload = {
  377. "grant_type": "urn:ietf:params:oauth:grant-type:uma-ticket",
  378. "permission": permission,
  379. "response_mode": "permissions",
  380. "audience": self.client_id,
  381. }
  382. self.connection.add_param_headers("Authorization", "Bearer " + token)
  383. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  384. return raise_error_from_response(data_raw, KeycloakPostError)
  385. def has_uma_access(self, token, permissions):
  386. """
  387. Determine whether user has uma permissions with specified user token
  388. :param token: user token
  389. :param permissions: list of uma permissions (resource:scope)
  390. :return: auth status
  391. """
  392. needed = build_permission_param(permissions)
  393. try:
  394. granted = self.uma_permissions(token, permissions)
  395. except (KeycloakPostError, KeycloakAuthenticationError) as e:
  396. if e.response_code == 403:
  397. return AuthStatus(
  398. is_logged_in=True, is_authorized=False, missing_permissions=needed
  399. )
  400. elif e.response_code == 401:
  401. return AuthStatus(
  402. is_logged_in=False, is_authorized=False, missing_permissions=needed
  403. )
  404. raise
  405. for resource_struct in granted:
  406. resource = resource_struct["rsname"]
  407. scopes = resource_struct.get("scopes", None)
  408. if not scopes:
  409. needed.discard(resource)
  410. continue
  411. for scope in scopes:
  412. needed.discard("{}#{}".format(resource, scope))
  413. return AuthStatus(
  414. is_logged_in=True, is_authorized=len(needed) == 0, missing_permissions=needed
  415. )