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.

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