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.

1524 lines
58 KiB

6 years ago
6 years ago
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 typing import Optional
  29. from jwcrypto import jwk, jwt
  30. from .authorization import Authorization
  31. from .connection import ConnectionManager
  32. from .exceptions import (
  33. KeycloakAuthenticationError,
  34. KeycloakAuthorizationConfigError,
  35. KeycloakDeprecationError,
  36. KeycloakGetError,
  37. KeycloakInvalidTokenError,
  38. KeycloakPostError,
  39. KeycloakPutError,
  40. KeycloakRPTNotFound,
  41. raise_error_from_response,
  42. )
  43. from .uma_permissions import AuthStatus, build_permission_param
  44. from .urls_patterns import (
  45. URL_AUTH,
  46. URL_CERTS,
  47. URL_CLIENT_REGISTRATION,
  48. URL_CLIENT_UPDATE,
  49. URL_DEVICE,
  50. URL_ENTITLEMENT,
  51. URL_INTROSPECT,
  52. URL_LOGOUT,
  53. URL_REALM,
  54. URL_TOKEN,
  55. URL_USERINFO,
  56. URL_WELL_KNOWN,
  57. )
  58. class KeycloakOpenID:
  59. """Keycloak OpenID client.
  60. :param server_url: Keycloak server url
  61. :param client_id: client id
  62. :param realm_name: realm name
  63. :param client_secret_key: client secret key
  64. :param verify: Boolean value to enable or disable certificate validation or a string
  65. containing a path to a CA bundle to use
  66. :param custom_headers: dict of custom header to pass to each HTML request
  67. :param proxies: dict of proxies to sent the request by.
  68. :param timeout: connection timeout in seconds
  69. :param cert: An SSL certificate used by the requested host to authenticate the client.
  70. Either a path to an SSL certificate file, or two-tuple of
  71. (certificate file, key file).
  72. """
  73. def __init__(
  74. self,
  75. server_url,
  76. realm_name,
  77. client_id,
  78. client_secret_key=None,
  79. verify=True,
  80. custom_headers=None,
  81. proxies=None,
  82. timeout=60,
  83. cert=None,
  84. ):
  85. """Init method.
  86. :param server_url: Keycloak server url
  87. :type server_url: str
  88. :param client_id: client id
  89. :type client_id: str
  90. :param realm_name: realm name
  91. :type realm_name: str
  92. :param client_secret_key: client secret key
  93. :type client_secret_key: str
  94. :param verify: Boolean value to enable or disable certificate validation or a string
  95. containing a path to a CA bundle to use
  96. :type verify: Union[bool,str]
  97. :param custom_headers: dict of custom header to pass to each HTML request
  98. :type custom_headers: dict
  99. :param proxies: dict of proxies to sent the request by.
  100. :type proxies: dict
  101. :param timeout: connection timeout in seconds
  102. :type timeout: int
  103. :param cert: An SSL certificate used by the requested host to authenticate the client.
  104. Either a path to an SSL certificate file, or two-tuple of
  105. (certificate file, key file).
  106. :type cert: Union[str,Tuple[str,str]]
  107. """
  108. self.client_id = client_id
  109. self.client_secret_key = client_secret_key
  110. self.realm_name = realm_name
  111. headers = custom_headers if custom_headers is not None else dict()
  112. self.connection = ConnectionManager(
  113. base_url=server_url,
  114. headers=headers,
  115. timeout=timeout,
  116. verify=verify,
  117. proxies=proxies,
  118. cert=cert,
  119. )
  120. self.authorization = Authorization()
  121. @property
  122. def client_id(self):
  123. """Get client id.
  124. :returns: Client id
  125. :rtype: str
  126. """
  127. return self._client_id
  128. @client_id.setter
  129. def client_id(self, value):
  130. self._client_id = value
  131. @property
  132. def client_secret_key(self):
  133. """Get the client secret key.
  134. :returns: Client secret key
  135. :rtype: str
  136. """
  137. return self._client_secret_key
  138. @client_secret_key.setter
  139. def client_secret_key(self, value):
  140. self._client_secret_key = value
  141. @property
  142. def realm_name(self):
  143. """Get the realm name.
  144. :returns: Realm name
  145. :rtype: str
  146. """
  147. return self._realm_name
  148. @realm_name.setter
  149. def realm_name(self, value):
  150. self._realm_name = value
  151. @property
  152. def connection(self):
  153. """Get connection.
  154. :returns: Connection manager object
  155. :rtype: ConnectionManager
  156. """
  157. return self._connection
  158. @connection.setter
  159. def connection(self, value):
  160. self._connection = value
  161. @property
  162. def authorization(self):
  163. """Get authorization.
  164. :returns: The authorization manager
  165. :rtype: Authorization
  166. """
  167. return self._authorization
  168. @authorization.setter
  169. def authorization(self, value):
  170. self._authorization = value
  171. def _add_secret_key(self, payload):
  172. """Add secret key if exists.
  173. :param payload: Payload
  174. :type payload: dict
  175. :returns: Payload with the secret key
  176. :rtype: dict
  177. """
  178. if self.client_secret_key:
  179. payload.update({"client_secret": self.client_secret_key})
  180. return payload
  181. def _build_name_role(self, role):
  182. """Build name of a role.
  183. :param role: Role name
  184. :type role: str
  185. :returns: Role path
  186. :rtype: str
  187. """
  188. return self.client_id + "/" + role
  189. def _token_info(self, token, method_token_info, **kwargs):
  190. """Getter for the token data.
  191. :param token: Token
  192. :type token: str
  193. :param method_token_info: Token info method to use
  194. :type method_token_info: str
  195. :param kwargs: Additional keyword arguments passed to the decode_token method
  196. :type kwargs: dict
  197. :returns: Token info
  198. :rtype: dict
  199. """
  200. if method_token_info == "introspect":
  201. token_info = self.introspect(token)
  202. else:
  203. token_info = self.decode_token(token, **kwargs)
  204. return token_info
  205. def well_known(self):
  206. """Get the well_known object.
  207. The most important endpoint to understand is the well-known configuration
  208. endpoint. It lists endpoints and other configuration options relevant to
  209. the OpenID Connect implementation in Keycloak.
  210. :returns: It lists endpoints and other configuration options relevant
  211. :rtype: dict
  212. """
  213. params_path = {"realm-name": self.realm_name}
  214. data_raw = self.connection.raw_get(URL_WELL_KNOWN.format(**params_path))
  215. return raise_error_from_response(data_raw, KeycloakGetError)
  216. def auth_url(self, redirect_uri, scope="email", state=""):
  217. """Get authorization URL endpoint.
  218. :param redirect_uri: Redirect url to receive oauth code
  219. :type redirect_uri: str
  220. :param scope: Scope of authorization request, split with the blank space
  221. :type scope: str
  222. :param state: State will be returned to the redirect_uri
  223. :type state: str
  224. :returns: Authorization URL Full Build
  225. :rtype: str
  226. """
  227. params_path = {
  228. "authorization-endpoint": self.well_known()["authorization_endpoint"],
  229. "client-id": self.client_id,
  230. "redirect-uri": redirect_uri,
  231. "scope": scope,
  232. "state": state,
  233. }
  234. return URL_AUTH.format(**params_path)
  235. def token(
  236. self,
  237. username="",
  238. password="",
  239. grant_type=["password"],
  240. code="",
  241. redirect_uri="",
  242. totp=None,
  243. scope="openid",
  244. **extra
  245. ):
  246. """Retrieve user token.
  247. The token endpoint is used to obtain tokens. Tokens can either be obtained by
  248. exchanging an authorization code or by supplying credentials directly depending on
  249. what flow is used. The token endpoint is also used to obtain new access tokens
  250. when they expire.
  251. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  252. :param username: Username
  253. :type username: str
  254. :param password: Password
  255. :type password: str
  256. :param grant_type: Grant type
  257. :type grant_type: str
  258. :param code: Code
  259. :type code: str
  260. :param redirect_uri: Redirect URI
  261. :type redirect_uri: str
  262. :param totp: Time-based one-time password
  263. :type totp: int
  264. :param scope: Scope, defaults to openid
  265. :type scope: str
  266. :param extra: Additional extra arguments
  267. :type extra: dict
  268. :returns: Keycloak token
  269. :rtype: dict
  270. """
  271. params_path = {"realm-name": self.realm_name}
  272. payload = {
  273. "username": username,
  274. "password": password,
  275. "client_id": self.client_id,
  276. "grant_type": grant_type,
  277. "code": code,
  278. "redirect_uri": redirect_uri,
  279. "scope": scope,
  280. }
  281. if extra:
  282. payload.update(extra)
  283. if totp:
  284. payload["totp"] = totp
  285. payload = self._add_secret_key(payload)
  286. content_type = self.connection.headers.get("Content-Type")
  287. self.connection.add_param_headers("Content-Type", "application/x-www-form-urlencoded")
  288. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  289. (
  290. self.connection.add_param_headers("Content-Type", content_type)
  291. if content_type
  292. else self.connection.del_param_headers("Content-Type")
  293. )
  294. return raise_error_from_response(data_raw, KeycloakPostError)
  295. def refresh_token(self, refresh_token, grant_type=["refresh_token"]):
  296. """Refresh the user token.
  297. The token endpoint is used to obtain tokens. Tokens can either be obtained by
  298. exchanging an authorization code or by supplying credentials directly depending on
  299. what flow is used. The token endpoint is also used to obtain new access tokens
  300. when they expire.
  301. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  302. :param refresh_token: Refresh token from Keycloak
  303. :type refresh_token: str
  304. :param grant_type: Grant type
  305. :type grant_type: str
  306. :returns: New token
  307. :rtype: dict
  308. """
  309. params_path = {"realm-name": self.realm_name}
  310. payload = {
  311. "client_id": self.client_id,
  312. "grant_type": grant_type,
  313. "refresh_token": refresh_token,
  314. }
  315. payload = self._add_secret_key(payload)
  316. content_type = self.connection.headers.get("Content-Type")
  317. self.connection.add_param_headers("Content-Type", "application/x-www-form-urlencoded")
  318. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  319. (
  320. self.connection.add_param_headers("Content-Type", content_type)
  321. if content_type
  322. else self.connection.del_param_headers("Content-Type")
  323. )
  324. return raise_error_from_response(data_raw, KeycloakPostError)
  325. def exchange_token(
  326. self,
  327. token: str,
  328. audience: Optional[str] = None,
  329. subject: Optional[str] = None,
  330. subject_token_type: Optional[str] = None,
  331. subject_issuer: Optional[str] = None,
  332. requested_issuer: Optional[str] = None,
  333. requested_token_type: str = "urn:ietf:params:oauth:token-type:refresh_token",
  334. scope: str = "openid",
  335. ) -> dict:
  336. """Exchange user token.
  337. Use a token to obtain an entirely different token. See
  338. https://www.keycloak.org/docs/latest/securing_apps/index.html#_token-exchange
  339. :param token: Access token
  340. :type token: str
  341. :param audience: Audience
  342. :type audience: str
  343. :param subject: Subject
  344. :type subject: str
  345. :param subject_token_type: Token Type specification
  346. :type subject_token_type: Optional[str]
  347. :param subject_issuer: Issuer
  348. :type subject_issuer: Optional[str]
  349. :param requested_issuer: Issuer
  350. :type requested_issuer: Optional[str]
  351. :param requested_token_type: Token type specification
  352. :type requested_token_type: str
  353. :param scope: Scope, defaults to openid
  354. :type scope: str
  355. :returns: Exchanged token
  356. :rtype: dict
  357. """
  358. params_path = {"realm-name": self.realm_name}
  359. payload = {
  360. "grant_type": ["urn:ietf:params:oauth:grant-type:token-exchange"],
  361. "client_id": self.client_id,
  362. "subject_token": token,
  363. "subject_token_type": subject_token_type,
  364. "subject_issuer": subject_issuer,
  365. "requested_token_type": requested_token_type,
  366. "audience": audience,
  367. "requested_subject": subject,
  368. "requested_issuer": requested_issuer,
  369. "scope": scope,
  370. }
  371. payload = self._add_secret_key(payload)
  372. content_type = self.connection.headers.get("Content-Type")
  373. self.connection.add_param_headers("Content-Type", "application/x-www-form-urlencoded")
  374. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  375. (
  376. self.connection.add_param_headers("Content-Type", content_type)
  377. if content_type
  378. else self.connection.del_param_headers("Content-Type")
  379. )
  380. return raise_error_from_response(data_raw, KeycloakPostError)
  381. def userinfo(self, token):
  382. """Get the user info object.
  383. The userinfo endpoint returns standard claims about the authenticated user,
  384. and is protected by a bearer token.
  385. http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
  386. :param token: Access token
  387. :type token: str
  388. :returns: Userinfo object
  389. :rtype: dict
  390. """
  391. orig_bearer = self.connection.headers.get("Authorization")
  392. self.connection.add_param_headers("Authorization", "Bearer " + token)
  393. params_path = {"realm-name": self.realm_name}
  394. data_raw = self.connection.raw_get(URL_USERINFO.format(**params_path))
  395. (
  396. self.connection.add_param_headers("Authorization", orig_bearer)
  397. if orig_bearer is not None
  398. else self.connection.del_param_headers("Authorization")
  399. )
  400. return raise_error_from_response(data_raw, KeycloakGetError)
  401. def logout(self, refresh_token):
  402. """Log out the authenticated user.
  403. :param refresh_token: Refresh token from Keycloak
  404. :type refresh_token: str
  405. :returns: Keycloak server response
  406. :rtype: dict
  407. """
  408. params_path = {"realm-name": self.realm_name}
  409. payload = {"client_id": self.client_id, "refresh_token": refresh_token}
  410. payload = self._add_secret_key(payload)
  411. data_raw = self.connection.raw_post(URL_LOGOUT.format(**params_path), data=payload)
  412. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  413. def certs(self):
  414. """Get certificates.
  415. The certificate endpoint returns the public keys enabled by the realm, encoded as a
  416. JSON Web Key (JWK). Depending on the realm settings there can be one or more keys enabled
  417. for verifying tokens.
  418. https://tools.ietf.org/html/rfc7517
  419. :returns: Certificates
  420. :rtype: dict
  421. """
  422. params_path = {"realm-name": self.realm_name}
  423. data_raw = self.connection.raw_get(URL_CERTS.format(**params_path))
  424. return raise_error_from_response(data_raw, KeycloakGetError)
  425. def public_key(self):
  426. """Retrieve the public key.
  427. The public key is exposed by the realm page directly.
  428. :returns: The public key
  429. :rtype: str
  430. """
  431. params_path = {"realm-name": self.realm_name}
  432. data_raw = self.connection.raw_get(URL_REALM.format(**params_path))
  433. return raise_error_from_response(data_raw, KeycloakGetError)["public_key"]
  434. def entitlement(self, token, resource_server_id):
  435. """Get entitlements from the token.
  436. Client applications can use a specific endpoint to obtain a special security token
  437. called a requesting party token (RPT). This token consists of all the entitlements
  438. (or permissions) for a user as a result of the evaluation of the permissions and
  439. authorization policies associated with the resources being requested. With an RPT,
  440. client applications can gain access to protected resources at the resource server.
  441. :param token: Access token
  442. :type token: str
  443. :param resource_server_id: Resource server ID
  444. :type resource_server_id: str
  445. :returns: Entitlements
  446. :rtype: dict
  447. """
  448. orig_bearer = self.connection.headers.get("Authorization")
  449. self.connection.add_param_headers("Authorization", "Bearer " + token)
  450. params_path = {"realm-name": self.realm_name, "resource-server-id": resource_server_id}
  451. data_raw = self.connection.raw_get(URL_ENTITLEMENT.format(**params_path))
  452. (
  453. self.connection.add_param_headers("Authorization", orig_bearer)
  454. if orig_bearer is not None
  455. else self.connection.del_param_headers("Authorization")
  456. )
  457. if data_raw.status_code == 404 or data_raw.status_code == 405:
  458. return raise_error_from_response(data_raw, KeycloakDeprecationError)
  459. return raise_error_from_response(data_raw, KeycloakGetError) # pragma: no cover
  460. def introspect(self, token, rpt=None, token_type_hint=None):
  461. """Introspect the user token.
  462. The introspection endpoint is used to retrieve the active state of a token.
  463. It is can only be invoked by confidential clients.
  464. https://tools.ietf.org/html/rfc7662
  465. :param token: Access token
  466. :type token: str
  467. :param rpt: Requesting party token
  468. :type rpt: str
  469. :param token_type_hint: Token type hint
  470. :type token_type_hint: str
  471. :returns: Token info
  472. :rtype: dict
  473. :raises KeycloakRPTNotFound: In case of RPT not specified
  474. """
  475. params_path = {"realm-name": self.realm_name}
  476. payload = {"client_id": self.client_id, "token": token}
  477. bearer_changed = False
  478. orig_bearer = None
  479. if token_type_hint == "requesting_party_token":
  480. if rpt:
  481. payload.update({"token": rpt, "token_type_hint": token_type_hint})
  482. orig_bearer = self.connection.headers.get("Authorization")
  483. self.connection.add_param_headers("Authorization", "Bearer " + token)
  484. bearer_changed = True
  485. else:
  486. raise KeycloakRPTNotFound("Can't found RPT.")
  487. payload = self._add_secret_key(payload)
  488. data_raw = self.connection.raw_post(URL_INTROSPECT.format(**params_path), data=payload)
  489. if bearer_changed:
  490. (
  491. self.connection.add_param_headers("Authorization", orig_bearer)
  492. if orig_bearer is not None
  493. else self.connection.del_param_headers("Authorization")
  494. )
  495. return raise_error_from_response(data_raw, KeycloakPostError)
  496. def decode_token(self, token, validate: bool = True, **kwargs):
  497. """Decode user token.
  498. A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data
  499. structure that represents a cryptographic key. This specification
  500. also defines a JWK Set JSON data structure that represents a set of
  501. JWKs. Cryptographic algorithms and identifiers for use with this
  502. specification are described in the separate JSON Web Algorithms (JWA)
  503. specification and IANA registries established by that specification.
  504. https://tools.ietf.org/html/rfc7517
  505. :param token: Keycloak token
  506. :type token: str
  507. :param validate: Determines whether the token should be validated with the public key.
  508. Defaults to True.
  509. :type validate: bool
  510. :param kwargs: Additional keyword arguments for jwcrypto's JWT object
  511. :type kwargs: dict
  512. :returns: Decoded token
  513. :rtype: dict
  514. """
  515. if validate:
  516. if "key" not in kwargs:
  517. key = (
  518. "-----BEGIN PUBLIC KEY-----\n"
  519. + self.public_key()
  520. + "\n-----END PUBLIC KEY-----"
  521. )
  522. key = jwk.JWK.from_pem(key.encode("utf-8"))
  523. kwargs["key"] = key
  524. key = kwargs.pop("key")
  525. leeway = kwargs.pop("leeway", 60)
  526. full_jwt = jwt.JWT(jwt=token, **kwargs)
  527. full_jwt.leeway = leeway
  528. full_jwt.validate(key)
  529. return jwt.json_decode(full_jwt.claims)
  530. else:
  531. full_jwt = jwt.JWT(jwt=token, **kwargs)
  532. full_jwt.token.objects["valid"] = True
  533. return json.loads(full_jwt.token.payload.decode("utf-8"))
  534. def load_authorization_config(self, path):
  535. """Load Keycloak settings (authorization).
  536. :param path: settings file (json)
  537. :type path: str
  538. """
  539. with open(path, "r") as fp:
  540. authorization_json = json.load(fp)
  541. self.authorization.load_config(authorization_json)
  542. def get_policies(self, token, method_token_info="introspect", **kwargs):
  543. """Get policies by user token.
  544. :param token: User token
  545. :type token: str
  546. :param method_token_info: Method for token info decoding
  547. :type method_token_info: str
  548. :param kwargs: Additional keyword arguments
  549. :type kwargs: dict
  550. :return: Policies
  551. :rtype: dict
  552. :raises KeycloakAuthorizationConfigError: In case of bad authorization configuration
  553. :raises KeycloakInvalidTokenError: In case of bad token
  554. """
  555. if not self.authorization.policies:
  556. raise KeycloakAuthorizationConfigError(
  557. "Keycloak settings not found. Load Authorization Keycloak settings."
  558. )
  559. token_info = self._token_info(token, method_token_info, **kwargs)
  560. if method_token_info == "introspect" and not token_info["active"]:
  561. raise KeycloakInvalidTokenError("Token expired or invalid.")
  562. user_resources = token_info["resource_access"].get(self.client_id)
  563. if not user_resources:
  564. return None
  565. policies = []
  566. for policy_name, policy in self.authorization.policies.items():
  567. for role in user_resources["roles"]:
  568. if self._build_name_role(role) in policy.roles:
  569. policies.append(policy)
  570. return list(set(policies))
  571. def get_permissions(self, token, method_token_info="introspect", **kwargs):
  572. """Get permission by user token .
  573. :param token: user token
  574. :type token: str
  575. :param method_token_info: Decode token method
  576. :type method_token_info: str
  577. :param kwargs: parameters for decode
  578. :type kwargs: dict
  579. :returns: permissions list
  580. :rtype: list
  581. :raises KeycloakAuthorizationConfigError: In case of bad authorization configuration
  582. :raises KeycloakInvalidTokenError: In case of bad token
  583. """
  584. if not self.authorization.policies:
  585. raise KeycloakAuthorizationConfigError(
  586. "Keycloak settings not found. Load Authorization Keycloak settings ."
  587. )
  588. token_info = self._token_info(token, method_token_info, **kwargs)
  589. if method_token_info == "introspect" and not token_info["active"]:
  590. raise KeycloakInvalidTokenError("Token expired or invalid.")
  591. user_resources = token_info["resource_access"].get(self.client_id)
  592. if not user_resources:
  593. return None
  594. permissions = []
  595. for policy_name, policy in self.authorization.policies.items():
  596. for role in user_resources["roles"]:
  597. if self._build_name_role(role) in policy.roles:
  598. permissions += policy.permissions
  599. return list(set(permissions))
  600. def uma_permissions(self, token, permissions=""):
  601. """Get UMA permissions by user token with requested permissions.
  602. The token endpoint is used to retrieve UMA permissions from Keycloak. It can only be
  603. invoked by confidential clients.
  604. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  605. :param token: user token
  606. :type token: str
  607. :param permissions: list of uma permissions list(resource:scope) requested by the user
  608. :type permissions: str
  609. :returns: Keycloak server response
  610. :rtype: dict
  611. """
  612. permission = build_permission_param(permissions)
  613. params_path = {"realm-name": self.realm_name}
  614. payload = {
  615. "grant_type": "urn:ietf:params:oauth:grant-type:uma-ticket",
  616. "permission": permission,
  617. "response_mode": "permissions",
  618. "audience": self.client_id,
  619. }
  620. orig_bearer = self.connection.headers.get("Authorization")
  621. self.connection.add_param_headers("Authorization", "Bearer " + token)
  622. content_type = self.connection.headers.get("Content-Type")
  623. self.connection.add_param_headers("Content-Type", "application/x-www-form-urlencoded")
  624. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  625. (
  626. self.connection.add_param_headers("Content-Type", content_type)
  627. if content_type
  628. else self.connection.del_param_headers("Content-Type")
  629. )
  630. (
  631. self.connection.add_param_headers("Authorization", orig_bearer)
  632. if orig_bearer is not None
  633. else self.connection.del_param_headers("Authorization")
  634. )
  635. return raise_error_from_response(data_raw, KeycloakPostError)
  636. def has_uma_access(self, token, permissions):
  637. """Determine whether user has uma permissions with specified user token.
  638. :param token: user token
  639. :type token: str
  640. :param permissions: list of uma permissions (resource:scope)
  641. :type permissions: str
  642. :return: Authentication status
  643. :rtype: AuthStatus
  644. :raises KeycloakAuthenticationError: In case of failed authentication
  645. :raises KeycloakPostError: In case of failed request to Keycloak
  646. """
  647. needed = build_permission_param(permissions)
  648. try:
  649. granted = self.uma_permissions(token, permissions)
  650. except (KeycloakPostError, KeycloakAuthenticationError) as e:
  651. if e.response_code == 403: # pragma: no cover
  652. return AuthStatus(
  653. is_logged_in=True, is_authorized=False, missing_permissions=needed
  654. )
  655. elif e.response_code == 401:
  656. return AuthStatus(
  657. is_logged_in=False, is_authorized=False, missing_permissions=needed
  658. )
  659. raise
  660. for resource_struct in granted:
  661. resource = resource_struct["rsname"]
  662. scopes = resource_struct.get("scopes", None)
  663. if not scopes:
  664. needed.discard(resource)
  665. continue
  666. for scope in scopes: # pragma: no cover
  667. needed.discard("{}#{}".format(resource, scope))
  668. return AuthStatus(
  669. is_logged_in=True, is_authorized=len(needed) == 0, missing_permissions=needed
  670. )
  671. def register_client(self, token: str, payload: dict):
  672. """Create a client.
  673. ClientRepresentation:
  674. https://www.keycloak.org/docs-api/24.0.2/rest-api/index.html#_clientrepresentation
  675. :param token: Initial access token
  676. :type token: str
  677. :param payload: ClientRepresentation
  678. :type payload: dict
  679. :return: Client Representation
  680. :rtype: dict
  681. """
  682. params_path = {"realm-name": self.realm_name}
  683. orig_bearer = self.connection.headers.get("Authorization")
  684. self.connection.add_param_headers("Authorization", "Bearer " + token)
  685. orig_content_type = self.connection.headers.get("Content-Type")
  686. self.connection.add_param_headers("Content-Type", "application/json")
  687. data_raw = self.connection.raw_post(
  688. URL_CLIENT_REGISTRATION.format(**params_path), data=json.dumps(payload)
  689. )
  690. (
  691. self.connection.add_param_headers("Authorization", orig_bearer)
  692. if orig_bearer is not None
  693. else self.connection.del_param_headers("Authorization")
  694. )
  695. (
  696. self.connection.add_param_headers("Content-Type", orig_content_type)
  697. if orig_content_type is not None
  698. else self.connection.del_param_headers("Content-Type")
  699. )
  700. return raise_error_from_response(data_raw, KeycloakPostError)
  701. def device(self):
  702. """Get device authorization grant.
  703. The device endpoint is used to obtain a user code verification and user authentication.
  704. The response contains a device_code, user_code, verification_uri,
  705. verification_uri_complete, expires_in (lifetime in seconds for device_code
  706. and user_code), and polling interval.
  707. Users can either follow the verification_uri and enter the user_code or
  708. follow the verification_uri_complete.
  709. After authenticating with valid credentials, users can obtain tokens using the
  710. "urn:ietf:params:oauth:grant-type:device_code" grant_type and the device_code.
  711. https://auth0.com/docs/get-started/authentication-and-authorization-flow/device-authorization-flow
  712. https://github.com/keycloak/keycloak-community/blob/main/design/oauth2-device-authorization-grant.md#how-to-try-it
  713. :returns: Device Authorization Response
  714. :rtype: dict
  715. """
  716. params_path = {"realm-name": self.realm_name}
  717. payload = {"client_id": self.client_id}
  718. payload = self._add_secret_key(payload)
  719. data_raw = self.connection.raw_post(URL_DEVICE.format(**params_path), data=payload)
  720. return raise_error_from_response(data_raw, KeycloakPostError)
  721. def update_client(self, token: str, client_id: str, payload: dict):
  722. """Update a client.
  723. ClientRepresentation:
  724. https://www.keycloak.org/docs-api/24.0.2/rest-api/index.html#_clientrepresentation
  725. :param token: registration access token
  726. :type token: str
  727. :param client_id: Keycloak client id
  728. :type client_id: str
  729. :param payload: ClientRepresentation
  730. :type payload: dict
  731. :return: Client Representation
  732. :rtype: dict
  733. """
  734. params_path = {"realm-name": self.realm_name, "client-id": client_id}
  735. orig_bearer = self.connection.headers.get("Authorization")
  736. self.connection.add_param_headers("Authorization", "Bearer " + token)
  737. orig_content_type = self.connection.headers.get("Content-Type")
  738. self.connection.add_param_headers("Content-Type", "application/json")
  739. # Keycloak complains if the clientId is not set in the payload
  740. if "clientId" not in payload:
  741. payload["clientId"] = client_id
  742. data_raw = self.connection.raw_put(
  743. URL_CLIENT_UPDATE.format(**params_path), data=json.dumps(payload)
  744. )
  745. (
  746. self.connection.add_param_headers("Authorization", orig_bearer)
  747. if orig_bearer is not None
  748. else self.connection.del_param_headers("Authorization")
  749. )
  750. (
  751. self.connection.add_param_headers("Content-Type", orig_content_type)
  752. if orig_content_type is not None
  753. else self.connection.del_param_headers("Content-Type")
  754. )
  755. return raise_error_from_response(data_raw, KeycloakPutError)
  756. async def a_well_known(self):
  757. """Get the well_known object asynchronously.
  758. The most important endpoint to understand is the well-known configuration
  759. endpoint. It lists endpoints and other configuration options relevant to
  760. the OpenID Connect implementation in Keycloak.
  761. :returns: It lists endpoints and other configuration options relevant
  762. :rtype: dict
  763. """
  764. params_path = {"realm-name": self.realm_name}
  765. data_raw = await self.connection.a_raw_get(URL_WELL_KNOWN.format(**params_path))
  766. return raise_error_from_response(data_raw, KeycloakGetError)
  767. async def a_auth_url(self, redirect_uri, scope="email", state=""):
  768. """Get authorization URL endpoint asynchronously.
  769. :param redirect_uri: Redirect url to receive oauth code
  770. :type redirect_uri: str
  771. :param scope: Scope of authorization request, split with the blank space
  772. :type scope: str
  773. :param state: State will be returned to the redirect_uri
  774. :type state: str
  775. :returns: Authorization URL Full Build
  776. :rtype: str
  777. """
  778. params_path = {
  779. "authorization-endpoint": (await self.a_well_known())["authorization_endpoint"],
  780. "client-id": self.client_id,
  781. "redirect-uri": redirect_uri,
  782. "scope": scope,
  783. "state": state,
  784. }
  785. return URL_AUTH.format(**params_path)
  786. async def a_token(
  787. self,
  788. username="",
  789. password="",
  790. grant_type=["password"],
  791. code="",
  792. redirect_uri="",
  793. totp=None,
  794. scope="openid",
  795. **extra
  796. ):
  797. """Retrieve user token asynchronously.
  798. The token endpoint is used to obtain tokens. Tokens can either be obtained by
  799. exchanging an authorization code or by supplying credentials directly depending on
  800. what flow is used. The token endpoint is also used to obtain new access tokens
  801. when they expire.
  802. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  803. :param username: Username
  804. :type username: str
  805. :param password: Password
  806. :type password: str
  807. :param grant_type: Grant type
  808. :type grant_type: str
  809. :param code: Code
  810. :type code: str
  811. :param redirect_uri: Redirect URI
  812. :type redirect_uri: str
  813. :param totp: Time-based one-time password
  814. :type totp: int
  815. :param scope: Scope, defaults to openid
  816. :type scope: str
  817. :param extra: Additional extra arguments
  818. :type extra: dict
  819. :returns: Keycloak token
  820. :rtype: dict
  821. """
  822. params_path = {"realm-name": self.realm_name}
  823. payload = {
  824. "username": username,
  825. "password": password,
  826. "client_id": self.client_id,
  827. "grant_type": grant_type,
  828. "code": code,
  829. "redirect_uri": redirect_uri,
  830. "scope": scope,
  831. }
  832. if extra:
  833. payload.update(extra)
  834. if totp:
  835. payload["totp"] = totp
  836. payload = self._add_secret_key(payload)
  837. content_type = self.connection.headers.get("Content-Type")
  838. self.connection.add_param_headers("Content-Type", "application/x-www-form-urlencoded")
  839. data_raw = await self.connection.a_raw_post(URL_TOKEN.format(**params_path), data=payload)
  840. (
  841. self.connection.add_param_headers("Content-Type", content_type)
  842. if content_type
  843. else self.connection.del_param_headers("Content-Type")
  844. )
  845. return raise_error_from_response(data_raw, KeycloakPostError)
  846. async def a_refresh_token(self, refresh_token, grant_type=["refresh_token"]):
  847. """Refresh the user token asynchronously.
  848. The token endpoint is used to obtain tokens. Tokens can either be obtained by
  849. exchanging an authorization code or by supplying credentials directly depending on
  850. what flow is used. The token endpoint is also used to obtain new access tokens
  851. when they expire.
  852. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  853. :param refresh_token: Refresh token from Keycloak
  854. :type refresh_token: str
  855. :param grant_type: Grant type
  856. :type grant_type: str
  857. :returns: New token
  858. :rtype: dict
  859. """
  860. params_path = {"realm-name": self.realm_name}
  861. payload = {
  862. "client_id": self.client_id,
  863. "grant_type": grant_type,
  864. "refresh_token": refresh_token,
  865. }
  866. payload = self._add_secret_key(payload)
  867. content_type = self.connection.headers.get("Content-Type")
  868. self.connection.add_param_headers("Content-Type", "application/x-www-form-urlencoded")
  869. data_raw = await self.connection.a_raw_post(URL_TOKEN.format(**params_path), data=payload)
  870. (
  871. self.connection.add_param_headers("Content-Type", content_type)
  872. if content_type
  873. else self.connection.del_param_headers("Content-Type")
  874. )
  875. return raise_error_from_response(data_raw, KeycloakPostError)
  876. async def a_exchange_token(
  877. self,
  878. token: str,
  879. audience: Optional[str] = None,
  880. subject: Optional[str] = None,
  881. subject_token_type: Optional[str] = None,
  882. subject_issuer: Optional[str] = None,
  883. requested_issuer: Optional[str] = None,
  884. requested_token_type: str = "urn:ietf:params:oauth:token-type:refresh_token",
  885. scope: str = "openid",
  886. ) -> dict:
  887. """Exchange user token asynchronously.
  888. Use a token to obtain an entirely different token. See
  889. https://www.keycloak.org/docs/latest/securing_apps/index.html#_token-exchange
  890. :param token: Access token
  891. :type token: str
  892. :param audience: Audience
  893. :type audience: str
  894. :param subject: Subject
  895. :type subject: str
  896. :param subject_token_type: Token Type specification
  897. :type subject_token_type: Optional[str]
  898. :param subject_issuer: Issuer
  899. :type subject_issuer: Optional[str]
  900. :param requested_issuer: Issuer
  901. :type requested_issuer: Optional[str]
  902. :param requested_token_type: Token type specification
  903. :type requested_token_type: str
  904. :param scope: Scope, defaults to openid
  905. :type scope: str
  906. :returns: Exchanged token
  907. :rtype: dict
  908. """
  909. params_path = {"realm-name": self.realm_name}
  910. payload = {
  911. "grant_type": ["urn:ietf:params:oauth:grant-type:token-exchange"],
  912. "client_id": self.client_id,
  913. "subject_token": token,
  914. "subject_token_type": subject_token_type,
  915. "subject_issuer": subject_issuer,
  916. "requested_token_type": requested_token_type,
  917. "audience": audience,
  918. "requested_subject": subject,
  919. "requested_issuer": requested_issuer,
  920. "scope": scope,
  921. }
  922. payload = self._add_secret_key(payload)
  923. content_type = self.connection.headers.get("Content-Type")
  924. self.connection.add_param_headers("Content-Type", "application/x-www-form-urlencoded")
  925. data_raw = await self.connection.a_raw_post(URL_TOKEN.format(**params_path), data=payload)
  926. (
  927. self.connection.add_param_headers("Content-Type", content_type)
  928. if content_type
  929. else self.connection.del_param_headers("Content-Type")
  930. )
  931. return raise_error_from_response(data_raw, KeycloakPostError)
  932. async def a_userinfo(self, token):
  933. """Get the user info object asynchronously.
  934. The userinfo endpoint returns standard claims about the authenticated user,
  935. and is protected by a bearer token.
  936. http://openid.net/specs/openid-connect-core-1_0.html#UserInfo
  937. :param token: Access token
  938. :type token: str
  939. :returns: Userinfo object
  940. :rtype: dict
  941. """
  942. orig_bearer = self.connection.headers.get("Authorization")
  943. self.connection.add_param_headers("Authorization", "Bearer " + token)
  944. params_path = {"realm-name": self.realm_name}
  945. data_raw = await self.connection.a_raw_get(URL_USERINFO.format(**params_path))
  946. (
  947. self.connection.add_param_headers("Authorization", orig_bearer)
  948. if orig_bearer is not None
  949. else self.connection.del_param_headers("Authorization")
  950. )
  951. return raise_error_from_response(data_raw, KeycloakGetError)
  952. async def a_logout(self, refresh_token):
  953. """Log out the authenticated user asynchronously.
  954. :param refresh_token: Refresh token from Keycloak
  955. :type refresh_token: str
  956. :returns: Keycloak server response
  957. :rtype: dict
  958. """
  959. params_path = {"realm-name": self.realm_name}
  960. payload = {"client_id": self.client_id, "refresh_token": refresh_token}
  961. payload = self._add_secret_key(payload)
  962. data_raw = await self.connection.a_raw_post(URL_LOGOUT.format(**params_path), data=payload)
  963. return raise_error_from_response(data_raw, KeycloakPostError, expected_codes=[204])
  964. async def a_certs(self):
  965. """Get certificates asynchronously.
  966. The certificate endpoint returns the public keys enabled by the realm, encoded as a
  967. JSON Web Key (JWK). Depending on the realm settings there can be one or more keys enabled
  968. for verifying tokens.
  969. https://tools.ietf.org/html/rfc7517
  970. :returns: Certificates
  971. :rtype: dict
  972. """
  973. params_path = {"realm-name": self.realm_name}
  974. data_raw = await self.connection.a_raw_get(URL_CERTS.format(**params_path))
  975. return raise_error_from_response(data_raw, KeycloakGetError)
  976. async def a_public_key(self):
  977. """Retrieve the public key asynchronously.
  978. The public key is exposed by the realm page directly.
  979. :returns: The public key
  980. :rtype: str
  981. """
  982. params_path = {"realm-name": self.realm_name}
  983. data_raw = await self.connection.a_raw_get(URL_REALM.format(**params_path))
  984. return raise_error_from_response(data_raw, KeycloakGetError)["public_key"]
  985. async def a_entitlement(self, token, resource_server_id):
  986. """Get entitlements from the token asynchronously.
  987. Client applications can use a specific endpoint to obtain a special security token
  988. called a requesting party token (RPT). This token consists of all the entitlements
  989. (or permissions) for a user as a result of the evaluation of the permissions and
  990. authorization policies associated with the resources being requested. With an RPT,
  991. client applications can gain access to protected resources at the resource server.
  992. :param token: Access token
  993. :type token: str
  994. :param resource_server_id: Resource server ID
  995. :type resource_server_id: str
  996. :returns: Entitlements
  997. :rtype: dict
  998. """
  999. orig_bearer = self.connection.headers.get("Authorization")
  1000. self.connection.add_param_headers("Authorization", "Bearer " + token)
  1001. params_path = {"realm-name": self.realm_name, "resource-server-id": resource_server_id}
  1002. data_raw = await self.connection.a_raw_get(URL_ENTITLEMENT.format(**params_path))
  1003. (
  1004. self.connection.add_param_headers("Authorization", orig_bearer)
  1005. if orig_bearer is not None
  1006. else self.connection.del_param_headers("Authorization")
  1007. )
  1008. if data_raw.status_code == 404 or data_raw.status_code == 405:
  1009. return raise_error_from_response(data_raw, KeycloakDeprecationError)
  1010. return raise_error_from_response(data_raw, KeycloakGetError) # pragma: no cover
  1011. async def a_introspect(self, token, rpt=None, token_type_hint=None):
  1012. """Introspect the user token asynchronously.
  1013. The introspection endpoint is used to retrieve the active state of a token.
  1014. It is can only be invoked by confidential clients.
  1015. https://tools.ietf.org/html/rfc7662
  1016. :param token: Access token
  1017. :type token: str
  1018. :param rpt: Requesting party token
  1019. :type rpt: str
  1020. :param token_type_hint: Token type hint
  1021. :type token_type_hint: str
  1022. :returns: Token info
  1023. :rtype: dict
  1024. :raises KeycloakRPTNotFound: In case of RPT not specified
  1025. """
  1026. params_path = {"realm-name": self.realm_name}
  1027. payload = {"client_id": self.client_id, "token": token}
  1028. orig_bearer = None
  1029. bearer_changed = False
  1030. if token_type_hint == "requesting_party_token":
  1031. if rpt:
  1032. payload.update({"token": rpt, "token_type_hint": token_type_hint})
  1033. orig_bearer = self.connection.headers.get("Authorization")
  1034. self.connection.add_param_headers("Authorization", "Bearer " + token)
  1035. bearer_changed = True
  1036. else:
  1037. raise KeycloakRPTNotFound("Can't found RPT.")
  1038. payload = self._add_secret_key(payload)
  1039. data_raw = await self.connection.a_raw_post(
  1040. URL_INTROSPECT.format(**params_path), data=payload
  1041. )
  1042. if bearer_changed:
  1043. (
  1044. self.connection.add_param_headers("Authorization", orig_bearer)
  1045. if orig_bearer is not None
  1046. else self.connection.del_param_headers("Authorization")
  1047. )
  1048. return raise_error_from_response(data_raw, KeycloakPostError)
  1049. async def a_decode_token(self, token, validate: bool = True, **kwargs):
  1050. """Decode user token asynchronously.
  1051. A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data
  1052. structure that represents a cryptographic key. This specification
  1053. also defines a JWK Set JSON data structure that represents a set of
  1054. JWKs. Cryptographic algorithms and identifiers for use with this
  1055. specification are described in the separate JSON Web Algorithms (JWA)
  1056. specification and IANA registries established by that specification.
  1057. https://tools.ietf.org/html/rfc7517
  1058. :param token: Keycloak token
  1059. :type token: str
  1060. :param validate: Determines whether the token should be validated with the public key.
  1061. Defaults to True.
  1062. :type validate: bool
  1063. :param kwargs: Additional keyword arguments for jwcrypto's JWT object
  1064. :type kwargs: dict
  1065. :returns: Decoded token
  1066. :rtype: dict
  1067. """
  1068. if validate:
  1069. if "key" not in kwargs:
  1070. key = (
  1071. "-----BEGIN PUBLIC KEY-----\n"
  1072. + await self.a_public_key()
  1073. + "\n-----END PUBLIC KEY-----"
  1074. )
  1075. key = jwk.JWK.from_pem(key.encode("utf-8"))
  1076. kwargs["key"] = key
  1077. full_jwt = jwt.JWT(jwt=token, **kwargs)
  1078. return jwt.json_decode(full_jwt.claims)
  1079. else:
  1080. full_jwt = jwt.JWT(jwt=token, **kwargs)
  1081. full_jwt.token.objects["valid"] = True
  1082. return json.loads(full_jwt.token.payload.decode("utf-8"))
  1083. async def a_load_authorization_config(self, path):
  1084. """Load Keycloak settings (authorization) asynchronously.
  1085. :param path: settings file (json)
  1086. :type path: str
  1087. """
  1088. with open(path, "r") as fp:
  1089. authorization_json = json.load(fp)
  1090. self.authorization.load_config(authorization_json)
  1091. async def a_get_policies(self, token, method_token_info="introspect", **kwargs):
  1092. """Get policies by user token asynchronously.
  1093. :param token: User token
  1094. :type token: str
  1095. :param method_token_info: Method for token info decoding
  1096. :type method_token_info: str
  1097. :param kwargs: Additional keyword arguments
  1098. :type kwargs: dict
  1099. :return: Policies
  1100. :rtype: dict
  1101. :raises KeycloakAuthorizationConfigError: In case of bad authorization configuration
  1102. :raises KeycloakInvalidTokenError: In case of bad token
  1103. """
  1104. if not self.authorization.policies:
  1105. raise KeycloakAuthorizationConfigError(
  1106. "Keycloak settings not found. Load Authorization Keycloak settings."
  1107. )
  1108. token_info = self._token_info(token, method_token_info, **kwargs)
  1109. if method_token_info == "introspect" and not token_info["active"]:
  1110. raise KeycloakInvalidTokenError("Token expired or invalid.")
  1111. user_resources = token_info["resource_access"].get(self.client_id)
  1112. if not user_resources:
  1113. return None
  1114. policies = []
  1115. for policy_name, policy in self.authorization.policies.items():
  1116. for role in user_resources["roles"]:
  1117. if self._build_name_role(role) in policy.roles:
  1118. policies.append(policy)
  1119. return list(set(policies))
  1120. async def a_get_permissions(self, token, method_token_info="introspect", **kwargs):
  1121. """Get permission by user token asynchronously.
  1122. :param token: user token
  1123. :type token: str
  1124. :param method_token_info: Decode token method
  1125. :type method_token_info: str
  1126. :param kwargs: parameters for decode
  1127. :type kwargs: dict
  1128. :returns: permissions list
  1129. :rtype: list
  1130. :raises KeycloakAuthorizationConfigError: In case of bad authorization configuration
  1131. :raises KeycloakInvalidTokenError: In case of bad token
  1132. """
  1133. if not self.authorization.policies:
  1134. raise KeycloakAuthorizationConfigError(
  1135. "Keycloak settings not found. Load Authorization Keycloak settings."
  1136. )
  1137. token_info = self._token_info(token, method_token_info, **kwargs)
  1138. if method_token_info == "introspect" and not token_info["active"]:
  1139. raise KeycloakInvalidTokenError("Token expired or invalid.")
  1140. user_resources = token_info["resource_access"].get(self.client_id)
  1141. if not user_resources:
  1142. return None
  1143. permissions = []
  1144. for policy_name, policy in self.authorization.policies.items():
  1145. for role in user_resources["roles"]:
  1146. if self._build_name_role(role) in policy.roles:
  1147. permissions += policy.permissions
  1148. return list(set(permissions))
  1149. async def a_uma_permissions(self, token, permissions=""):
  1150. """Get UMA permissions by user token with requested permissions asynchronously.
  1151. The token endpoint is used to retrieve UMA permissions from Keycloak. It can only be
  1152. invoked by confidential clients.
  1153. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  1154. :param token: user token
  1155. :type token: str
  1156. :param permissions: list of uma permissions list(resource:scope) requested by the user
  1157. :type permissions: str
  1158. :returns: Keycloak server response
  1159. :rtype: dict
  1160. """
  1161. permission = build_permission_param(permissions)
  1162. params_path = {"realm-name": self.realm_name}
  1163. payload = {
  1164. "grant_type": "urn:ietf:params:oauth:grant-type:uma-ticket",
  1165. "permission": permission,
  1166. "response_mode": "permissions",
  1167. "audience": self.client_id,
  1168. }
  1169. orig_bearer = self.connection.headers.get("Authorization")
  1170. self.connection.add_param_headers("Authorization", "Bearer " + token)
  1171. content_type = self.connection.headers.get("Content-Type")
  1172. self.connection.add_param_headers("Content-Type", "application/x-www-form-urlencoded")
  1173. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  1174. (
  1175. self.connection.add_param_headers("Content-Type", content_type)
  1176. if content_type
  1177. else self.connection.del_param_headers("Content-Type")
  1178. )
  1179. (
  1180. self.connection.add_param_headers("Authorization", orig_bearer)
  1181. if orig_bearer is not None
  1182. else self.connection.del_param_headers("Authorization")
  1183. )
  1184. return raise_error_from_response(data_raw, KeycloakPostError)
  1185. async def a_has_uma_access(self, token, permissions):
  1186. """Determine whether user has uma permissions with specified user token asynchronously.
  1187. :param token: user token
  1188. :type token: str
  1189. :param permissions: list of uma permissions (resource:scope)
  1190. :type permissions: str
  1191. :return: Authentication status
  1192. :rtype: AuthStatus
  1193. :raises KeycloakAuthenticationError: In case of failed authentication
  1194. :raises KeycloakPostError: In case of failed request to Keycloak
  1195. """
  1196. needed = build_permission_param(permissions)
  1197. try:
  1198. granted = await self.a_uma_permissions(token, permissions)
  1199. except (KeycloakPostError, KeycloakAuthenticationError) as e:
  1200. if e.response_code == 403: # pragma: no cover
  1201. return AuthStatus(
  1202. is_logged_in=True, is_authorized=False, missing_permissions=needed
  1203. )
  1204. elif e.response_code == 401:
  1205. return AuthStatus(
  1206. is_logged_in=False, is_authorized=False, missing_permissions=needed
  1207. )
  1208. raise
  1209. for resource_struct in granted:
  1210. resource = resource_struct["rsname"]
  1211. scopes = resource_struct.get("scopes", None)
  1212. if not scopes:
  1213. needed.discard(resource)
  1214. continue
  1215. for scope in scopes: # pragma: no cover
  1216. needed.discard("{}#{}".format(resource, scope))
  1217. return AuthStatus(
  1218. is_logged_in=True, is_authorized=len(needed) == 0, missing_permissions=needed
  1219. )
  1220. async def a_register_client(self, token: str, payload: dict):
  1221. """Create a client asynchronously.
  1222. ClientRepresentation:
  1223. https://www.keycloak.org/docs-api/24.0.2/rest-api/index.html#_clientrepresentation
  1224. :param token: Initial access token
  1225. :type token: str
  1226. :param payload: ClientRepresentation
  1227. :type payload: dict
  1228. :return: Client Representation
  1229. :rtype: dict
  1230. """
  1231. params_path = {"realm-name": self.realm_name}
  1232. orig_bearer = self.connection.headers.get("Authorization")
  1233. self.connection.add_param_headers("Authorization", "Bearer " + token)
  1234. orig_content_type = self.connection.headers.get("Content-Type")
  1235. self.connection.add_param_headers("Content-Type", "application/json")
  1236. data_raw = await self.connection.a_raw_post(
  1237. URL_CLIENT_REGISTRATION.format(**params_path), data=json.dumps(payload)
  1238. )
  1239. (
  1240. self.connection.add_param_headers("Authorization", orig_bearer)
  1241. if orig_bearer is not None
  1242. else self.connection.del_param_headers("Authorization")
  1243. )
  1244. (
  1245. self.connection.add_param_headers("Content-Type", orig_content_type)
  1246. if orig_content_type is not None
  1247. else self.connection.del_param_headers("Content-Type")
  1248. )
  1249. return raise_error_from_response(data_raw, KeycloakPostError)
  1250. async def a_device(self):
  1251. """Get device authorization grant asynchronously.
  1252. The device endpoint is used to obtain a user code verification and user authentication.
  1253. The response contains a device_code, user_code, verification_uri,
  1254. verification_uri_complete, expires_in (lifetime in seconds for device_code
  1255. and user_code), and polling interval.
  1256. Users can either follow the verification_uri and enter the user_code or
  1257. follow the verification_uri_complete.
  1258. After authenticating with valid credentials, users can obtain tokens using the
  1259. "urn:ietf:params:oauth:grant-type:device_code" grant_type and the device_code.
  1260. https://auth0.com/docs/get-started/authentication-and-authorization-flow/device-authorization-flow
  1261. https://github.com/keycloak/keycloak-community/blob/main/design/oauth2-device-authorization-grant.md#how-to-try-it
  1262. :returns: Device Authorization Response
  1263. :rtype: dict
  1264. """
  1265. params_path = {"realm-name": self.realm_name}
  1266. payload = {"client_id": self.client_id}
  1267. payload = self._add_secret_key(payload)
  1268. data_raw = await self.connection.a_raw_post(URL_DEVICE.format(**params_path), data=payload)
  1269. return raise_error_from_response(data_raw, KeycloakPostError)
  1270. async def a_update_client(self, token: str, client_id: str, payload: dict):
  1271. """Update a client asynchronously.
  1272. ClientRepresentation:
  1273. https://www.keycloak.org/docs-api/24.0.2/rest-api/index.html#_clientrepresentation
  1274. :param token: registration access token
  1275. :type token: str
  1276. :param client_id: Keycloak client id
  1277. :type client_id: str
  1278. :param payload: ClientRepresentation
  1279. :type payload: dict
  1280. :return: Client Representation
  1281. :rtype: dict
  1282. """
  1283. params_path = {"realm-name": self.realm_name, "client-id": client_id}
  1284. orig_bearer = self.connection.headers.get("Authorization")
  1285. self.connection.add_param_headers("Authorization", "Bearer " + token)
  1286. orig_content_type = self.connection.headers.get("Content-Type")
  1287. self.connection.add_param_headers("Content-Type", "application/json")
  1288. # Keycloak complains if the clientId is not set in the payload
  1289. if "clientId" not in payload:
  1290. payload["clientId"] = client_id
  1291. data_raw = await self.connection.a_raw_put(
  1292. URL_CLIENT_UPDATE.format(**params_path), data=json.dumps(payload)
  1293. )
  1294. (
  1295. self.connection.add_param_headers("Authorization", orig_bearer)
  1296. if orig_bearer is not None
  1297. else self.connection.del_param_headers("Authorization")
  1298. )
  1299. (
  1300. self.connection.add_param_headers("Content-Type", orig_content_type)
  1301. if orig_content_type is not None
  1302. else self.connection.del_param_headers("Content-Type")
  1303. )
  1304. return raise_error_from_response(data_raw, KeycloakPutError)