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.

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