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.

703 lines
24 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_CLIENT_REGISTRATION,
  46. URL_ENTITLEMENT,
  47. URL_INTROSPECT,
  48. URL_LOGOUT,
  49. URL_REALM,
  50. URL_TOKEN,
  51. URL_USERINFO,
  52. URL_WELL_KNOWN,
  53. )
  54. class KeycloakOpenID:
  55. """Keycloak OpenID client.
  56. :param server_url: Keycloak server url
  57. :param client_id: client id
  58. :param realm_name: realm name
  59. :param client_secret_key: client secret key
  60. :param verify: True if want check connection SSL
  61. :param custom_headers: dict of custom header to pass to each HTML request
  62. :param proxies: dict of proxies to sent the request by.
  63. :param timeout: connection timeout in seconds
  64. """
  65. def __init__(
  66. self,
  67. server_url,
  68. realm_name,
  69. client_id,
  70. client_secret_key=None,
  71. verify=True,
  72. custom_headers=None,
  73. proxies=None,
  74. timeout=60,
  75. ):
  76. """Init method.
  77. :param server_url: Keycloak server url
  78. :type server_url: str
  79. :param client_id: client id
  80. :type client_id: str
  81. :param realm_name: realm name
  82. :type realm_name: str
  83. :param client_secret_key: client secret key
  84. :type client_secret_key: str
  85. :param verify: True if want check connection SSL
  86. :type verify: bool
  87. :param custom_headers: dict of custom header to pass to each HTML request
  88. :type custom_headers: dict
  89. :param proxies: dict of proxies to sent the request by.
  90. :type proxies: dict
  91. :param timeout: connection timeout in seconds
  92. :type timeout: int
  93. """
  94. self.client_id = client_id
  95. self.client_secret_key = client_secret_key
  96. self.realm_name = realm_name
  97. headers = custom_headers if custom_headers is not None else dict()
  98. self.connection = ConnectionManager(
  99. base_url=server_url, headers=headers, timeout=timeout, verify=verify, proxies=proxies
  100. )
  101. self.authorization = Authorization()
  102. @property
  103. def client_id(self):
  104. """Get client id.
  105. :returns: Client id
  106. :rtype: str
  107. """
  108. return self._client_id
  109. @client_id.setter
  110. def client_id(self, value):
  111. self._client_id = value
  112. @property
  113. def client_secret_key(self):
  114. """Get the client secret key.
  115. :returns: Client secret key
  116. :rtype: str
  117. """
  118. return self._client_secret_key
  119. @client_secret_key.setter
  120. def client_secret_key(self, value):
  121. self._client_secret_key = value
  122. @property
  123. def realm_name(self):
  124. """Get the realm name.
  125. :returns: Realm name
  126. :rtype: str
  127. """
  128. return self._realm_name
  129. @realm_name.setter
  130. def realm_name(self, value):
  131. self._realm_name = value
  132. @property
  133. def connection(self):
  134. """Get connection.
  135. :returns: Connection manager object
  136. :rtype: ConnectionManager
  137. """
  138. return self._connection
  139. @connection.setter
  140. def connection(self, value):
  141. self._connection = value
  142. @property
  143. def authorization(self):
  144. """Get authorization.
  145. :returns: The authorization manager
  146. :rtype: Authorization
  147. """
  148. return self._authorization
  149. @authorization.setter
  150. def authorization(self, value):
  151. self._authorization = value
  152. def _add_secret_key(self, payload):
  153. """Add secret key if exists.
  154. :param payload: Payload
  155. :type payload: dict
  156. :returns: Payload with the secret key
  157. :rtype: dict
  158. """
  159. if self.client_secret_key:
  160. payload.update({"client_secret": self.client_secret_key})
  161. return payload
  162. def _build_name_role(self, role):
  163. """Build name of a role.
  164. :param role: Role name
  165. :type role: str
  166. :returns: Role path
  167. :rtype: str
  168. """
  169. return self.client_id + "/" + role
  170. def _token_info(self, token, method_token_info, **kwargs):
  171. """Getter for the token data.
  172. :param token: Token
  173. :type token: str
  174. :param method_token_info: Token info method to use
  175. :type method_token_info: str
  176. :param kwargs: Additional keyword arguments
  177. :type kwargs: dict
  178. :returns: Token info
  179. :rtype: dict
  180. """
  181. if method_token_info == "introspect":
  182. token_info = self.introspect(token)
  183. else:
  184. token_info = self.decode_token(token, **kwargs)
  185. return token_info
  186. def well_known(self):
  187. """Get the well_known object.
  188. The most important endpoint to understand is the well-known configuration
  189. endpoint. It lists endpoints and other configuration options relevant to
  190. the OpenID Connect implementation in Keycloak.
  191. :returns: It lists endpoints and other configuration options relevant
  192. :rtype: dict
  193. """
  194. params_path = {"realm-name": self.realm_name}
  195. data_raw = self.connection.raw_get(URL_WELL_KNOWN.format(**params_path))
  196. return raise_error_from_response(data_raw, KeycloakGetError)
  197. def auth_url(self, redirect_uri, scope="email", state=""):
  198. """Get authorization URL endpoint.
  199. :param redirect_uri: Redirect url to receive oauth code
  200. :type redirect_uri: str
  201. :param scope: Scope of authorization request, split with the blank space
  202. :type scope: str
  203. :param state: State will be returned to the redirect_uri
  204. :type state: str
  205. :returns: Authorization URL Full Build
  206. :rtype: str
  207. """
  208. params_path = {
  209. "authorization-endpoint": self.well_known()["authorization_endpoint"],
  210. "client-id": self.client_id,
  211. "redirect-uri": redirect_uri,
  212. "scope": scope,
  213. "state": state,
  214. }
  215. return URL_AUTH.format(**params_path)
  216. def token(
  217. self,
  218. username="",
  219. password="",
  220. grant_type=["password"],
  221. code="",
  222. redirect_uri="",
  223. totp=None,
  224. scope="openid",
  225. **extra
  226. ):
  227. """Retrieve user token.
  228. The token endpoint is used to obtain tokens. Tokens can either be obtained by
  229. exchanging an authorization code or by supplying credentials directly depending on
  230. what flow is used. The token endpoint is also used to obtain new access tokens
  231. when they expire.
  232. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  233. :param username: Username
  234. :type username: str
  235. :param password: Password
  236. :type password: str
  237. :param grant_type: Grant type
  238. :type grant_type: str
  239. :param code: Code
  240. :type code: str
  241. :param redirect_uri: Redirect URI
  242. :type redirect_uri: str
  243. :param totp: Time-based one-time password
  244. :type totp: int
  245. :param scope: Scope, defaults to openid
  246. :type scope: str
  247. :param extra: Additional extra arguments
  248. :type extra: dict
  249. :returns: Keycloak token
  250. :rtype: dict
  251. """
  252. params_path = {"realm-name": self.realm_name}
  253. payload = {
  254. "username": username,
  255. "password": password,
  256. "client_id": self.client_id,
  257. "grant_type": grant_type,
  258. "code": code,
  259. "redirect_uri": redirect_uri,
  260. "scope": scope,
  261. }
  262. if extra:
  263. payload.update(extra)
  264. if totp:
  265. payload["totp"] = totp
  266. payload = self._add_secret_key(payload)
  267. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  268. return raise_error_from_response(data_raw, KeycloakPostError)
  269. def refresh_token(self, refresh_token, grant_type=["refresh_token"]):
  270. """Refresh the user token.
  271. The token endpoint is used to obtain tokens. Tokens can either be obtained by
  272. exchanging an authorization code or by supplying credentials directly depending on
  273. what flow is used. The token endpoint is also used to obtain new access tokens
  274. when they expire.
  275. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  276. :param refresh_token: Refresh token from Keycloak
  277. :type refresh_token: str
  278. :param grant_type: Grant type
  279. :type grant_type: str
  280. :returns: New token
  281. :rtype: dict
  282. """
  283. params_path = {"realm-name": self.realm_name}
  284. payload = {
  285. "client_id": self.client_id,
  286. "grant_type": grant_type,
  287. "refresh_token": refresh_token,
  288. }
  289. payload = self._add_secret_key(payload)
  290. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  291. return raise_error_from_response(data_raw, KeycloakPostError)
  292. def exchange_token(
  293. self,
  294. token: str,
  295. client_id: str,
  296. audience: str,
  297. subject: str,
  298. requested_token_type: str = "urn:ietf:params:oauth:token-type:refresh_token",
  299. scope: str = "openid",
  300. ) -> dict:
  301. """Exchange user token.
  302. Use a token to obtain an entirely different token. See
  303. https://www.keycloak.org/docs/latest/securing_apps/index.html#_token-exchange
  304. :param token: Access token
  305. :type token: str
  306. :param client_id: Client id
  307. :type client_id: str
  308. :param audience: Audience
  309. :type audience: str
  310. :param subject: Subject
  311. :type subject: str
  312. :param requested_token_type: Token type specification
  313. :type requested_token_type: str
  314. :param scope: Scope, defaults to openid
  315. :type scope: str
  316. :returns: Exchanged token
  317. :rtype: dict
  318. """
  319. params_path = {"realm-name": self.realm_name}
  320. payload = {
  321. "grant_type": ["urn:ietf:params:oauth:grant-type:token-exchange"],
  322. "client_id": client_id,
  323. "subject_token": token,
  324. "requested_token_type": requested_token_type,
  325. "audience": audience,
  326. "requested_subject": subject,
  327. "scope": scope,
  328. }
  329. payload = self._add_secret_key(payload)
  330. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  331. return raise_error_from_response(data_raw, KeycloakPostError)
  332. def userinfo(self, token):
  333. """Get the user info object.
  334. The userinfo endpoint returns standard claims about the authenticated user,
  335. and is protected by a bearer token.
  336. http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
  337. :param token: Access token
  338. :type token: str
  339. :returns: Userinfo object
  340. :rtype: dict
  341. """
  342. self.connection.add_param_headers("Authorization", "Bearer " + token)
  343. params_path = {"realm-name": self.realm_name}
  344. data_raw = self.connection.raw_get(URL_USERINFO.format(**params_path))
  345. return raise_error_from_response(data_raw, KeycloakGetError)
  346. def logout(self, refresh_token):
  347. """Log out the authenticated user.
  348. :param refresh_token: Refresh token from Keycloak
  349. :type refresh_token: str
  350. :returns: Keycloak server response
  351. :rtype: dict
  352. """
  353. params_path = {"realm-name": self.realm_name}
  354. payload = {"client_id": self.client_id, "refresh_token": refresh_token}
  355. payload = self._add_secret_key(payload)
  356. data_raw = self.connection.raw_post(URL_LOGOUT.format(**params_path), data=payload)
  357. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  358. def certs(self):
  359. """Get certificates.
  360. The certificate endpoint returns the public keys enabled by the realm, encoded as a
  361. JSON Web Key (JWK). Depending on the realm settings there can be one or more keys enabled
  362. for verifying tokens.
  363. https://tools.ietf.org/html/rfc7517
  364. :returns: Certificates
  365. :rtype: dict
  366. """
  367. params_path = {"realm-name": self.realm_name}
  368. data_raw = self.connection.raw_get(URL_CERTS.format(**params_path))
  369. return raise_error_from_response(data_raw, KeycloakGetError)
  370. def public_key(self):
  371. """Retrieve the public key.
  372. The public key is exposed by the realm page directly.
  373. :returns: The public key
  374. :rtype: str
  375. """
  376. params_path = {"realm-name": self.realm_name}
  377. data_raw = self.connection.raw_get(URL_REALM.format(**params_path))
  378. return raise_error_from_response(data_raw, KeycloakGetError)["public_key"]
  379. def entitlement(self, token, resource_server_id):
  380. """Get entitlements from the token.
  381. Client applications can use a specific endpoint to obtain a special security token
  382. called a requesting party token (RPT). This token consists of all the entitlements
  383. (or permissions) for a user as a result of the evaluation of the permissions and
  384. authorization policies associated with the resources being requested. With an RPT,
  385. client applications can gain access to protected resources at the resource server.
  386. :param token: Access token
  387. :type token: str
  388. :param resource_server_id: Resource server ID
  389. :type resource_server_id: str
  390. :returns: Entitlements
  391. :rtype: dict
  392. """
  393. self.connection.add_param_headers("Authorization", "Bearer " + token)
  394. params_path = {"realm-name": self.realm_name, "resource-server-id": resource_server_id}
  395. data_raw = self.connection.raw_get(URL_ENTITLEMENT.format(**params_path))
  396. if data_raw.status_code == 404:
  397. return raise_error_from_response(data_raw, KeycloakDeprecationError)
  398. return raise_error_from_response(data_raw, KeycloakGetError) # pragma: no cover
  399. def introspect(self, token, rpt=None, token_type_hint=None):
  400. """Introspect the user token.
  401. The introspection endpoint is used to retrieve the active state of a token.
  402. It is can only be invoked by confidential clients.
  403. https://tools.ietf.org/html/rfc7662
  404. :param token: Access token
  405. :type token: str
  406. :param rpt: Requesting party token
  407. :type rpt: str
  408. :param token_type_hint: Token type hint
  409. :type token_type_hint: str
  410. :returns: Token info
  411. :rtype: dict
  412. :raises KeycloakRPTNotFound: In case of RPT not specified
  413. """
  414. params_path = {"realm-name": self.realm_name}
  415. payload = {"client_id": self.client_id, "token": token}
  416. if token_type_hint == "requesting_party_token":
  417. if rpt:
  418. payload.update({"token": rpt, "token_type_hint": token_type_hint})
  419. self.connection.add_param_headers("Authorization", "Bearer " + token)
  420. else:
  421. raise KeycloakRPTNotFound("Can't found RPT.")
  422. payload = self._add_secret_key(payload)
  423. data_raw = self.connection.raw_post(URL_INTROSPECT.format(**params_path), data=payload)
  424. return raise_error_from_response(data_raw, KeycloakPostError)
  425. def decode_token(self, token, key, algorithms=["RS256"], **kwargs):
  426. """Decode user token.
  427. A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data
  428. structure that represents a cryptographic key. This specification
  429. also defines a JWK Set JSON data structure that represents a set of
  430. JWKs. Cryptographic algorithms and identifiers for use with this
  431. specification are described in the separate JSON Web Algorithms (JWA)
  432. specification and IANA registries established by that specification.
  433. https://tools.ietf.org/html/rfc7517
  434. :param token: Keycloak token
  435. :type token: str
  436. :param key: Decode key
  437. :type key: str
  438. :param algorithms: Algorithms to use for decoding
  439. :type algorithms: list[str]
  440. :param kwargs: Keyword arguments
  441. :type kwargs: dict
  442. :returns: Decoded token
  443. :rtype: dict
  444. """
  445. return jwt.decode(token, key, algorithms=algorithms, audience=self.client_id, **kwargs)
  446. def load_authorization_config(self, path):
  447. """Load Keycloak settings (authorization).
  448. :param path: settings file (json)
  449. :type path: str
  450. """
  451. with open(path, "r") as fp:
  452. authorization_json = json.load(fp)
  453. self.authorization.load_config(authorization_json)
  454. def get_policies(self, token, method_token_info="introspect", **kwargs):
  455. """Get policies by user token.
  456. :param token: User token
  457. :type token: str
  458. :param method_token_info: Method for token info decoding
  459. :type method_token_info: str
  460. :param kwargs: Additional keyword arguments
  461. :type kwargs: dict
  462. :return: Policies
  463. :rtype: dict
  464. :raises KeycloakAuthorizationConfigError: In case of bad authorization configuration
  465. :raises KeycloakInvalidTokenError: In case of bad token
  466. """
  467. if not self.authorization.policies:
  468. raise KeycloakAuthorizationConfigError(
  469. "Keycloak settings not found. Load Authorization Keycloak settings."
  470. )
  471. token_info = self._token_info(token, method_token_info, **kwargs)
  472. if method_token_info == "introspect" and not token_info["active"]:
  473. raise KeycloakInvalidTokenError("Token expired or invalid.")
  474. user_resources = token_info["resource_access"].get(self.client_id)
  475. if not user_resources:
  476. return None
  477. policies = []
  478. for policy_name, policy in self.authorization.policies.items():
  479. for role in user_resources["roles"]:
  480. if self._build_name_role(role) in policy.roles:
  481. policies.append(policy)
  482. return list(set(policies))
  483. def get_permissions(self, token, method_token_info="introspect", **kwargs):
  484. """Get permission by user token.
  485. :param token: user token
  486. :type token: str
  487. :param method_token_info: Decode token method
  488. :type method_token_info: str
  489. :param kwargs: parameters for decode
  490. :type kwargs: dict
  491. :returns: permissions list
  492. :rtype: list
  493. :raises KeycloakAuthorizationConfigError: In case of bad authorization configuration
  494. :raises KeycloakInvalidTokenError: In case of bad token
  495. """
  496. if not self.authorization.policies:
  497. raise KeycloakAuthorizationConfigError(
  498. "Keycloak settings not found. Load Authorization Keycloak settings."
  499. )
  500. token_info = self._token_info(token, method_token_info, **kwargs)
  501. if method_token_info == "introspect" and not token_info["active"]:
  502. raise KeycloakInvalidTokenError("Token expired or invalid.")
  503. user_resources = token_info["resource_access"].get(self.client_id)
  504. if not user_resources:
  505. return None
  506. permissions = []
  507. for policy_name, policy in self.authorization.policies.items():
  508. for role in user_resources["roles"]:
  509. if self._build_name_role(role) in policy.roles:
  510. permissions += policy.permissions
  511. return list(set(permissions))
  512. def uma_permissions(self, token, permissions=""):
  513. """Get UMA permissions by user token with requested permissions.
  514. The token endpoint is used to retrieve UMA permissions from Keycloak. It can only be
  515. invoked by confidential clients.
  516. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  517. :param token: user token
  518. :type token: str
  519. :param permissions: list of uma permissions list(resource:scope) requested by the user
  520. :type permissions: str
  521. :returns: Keycloak server response
  522. :rtype: dict
  523. """
  524. permission = build_permission_param(permissions)
  525. params_path = {"realm-name": self.realm_name}
  526. payload = {
  527. "grant_type": "urn:ietf:params:oauth:grant-type:uma-ticket",
  528. "permission": permission,
  529. "response_mode": "permissions",
  530. "audience": self.client_id,
  531. }
  532. self.connection.add_param_headers("Authorization", "Bearer " + token)
  533. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  534. return raise_error_from_response(data_raw, KeycloakPostError)
  535. def has_uma_access(self, token, permissions):
  536. """Determine whether user has uma permissions with specified user token.
  537. :param token: user token
  538. :type token: str
  539. :param permissions: list of uma permissions (resource:scope)
  540. :type permissions: str
  541. :return: Authentication status
  542. :rtype: AuthStatus
  543. :raises KeycloakAuthenticationError: In case of failed authentication
  544. :raises KeycloakPostError: In case of failed request to Keycloak
  545. """
  546. needed = build_permission_param(permissions)
  547. try:
  548. granted = self.uma_permissions(token, permissions)
  549. except (KeycloakPostError, KeycloakAuthenticationError) as e:
  550. if e.response_code == 403: # pragma: no cover
  551. return AuthStatus(
  552. is_logged_in=True, is_authorized=False, missing_permissions=needed
  553. )
  554. elif e.response_code == 401:
  555. return AuthStatus(
  556. is_logged_in=False, is_authorized=False, missing_permissions=needed
  557. )
  558. raise
  559. for resource_struct in granted:
  560. resource = resource_struct["rsname"]
  561. scopes = resource_struct.get("scopes", None)
  562. if not scopes:
  563. needed.discard(resource)
  564. continue
  565. for scope in scopes: # pragma: no cover
  566. needed.discard("{}#{}".format(resource, scope))
  567. return AuthStatus(
  568. is_logged_in=True, is_authorized=len(needed) == 0, missing_permissions=needed
  569. )
  570. def register_client(self, token: str, payload: dict):
  571. """Create a client.
  572. ClientRepresentation:
  573. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  574. :param token: Initial access token
  575. :type token: str
  576. :param payload: ClientRepresentation
  577. :type payload: dict
  578. :return: Client Representation
  579. :rtype: dict
  580. """
  581. params_path = {"realm-name": self.realm_name}
  582. self.connection.add_param_headers("Authorization", "Bearer " + token)
  583. self.connection.add_param_headers("Content-Type", "application/json")
  584. data_raw = self.connection.raw_post(
  585. URL_CLIENT_REGISTRATION.format(**params_path), data=json.dumps(payload)
  586. )
  587. return raise_error_from_response(data_raw, KeycloakPostError)