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.

771 lines
27 KiB

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 jose import 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
  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, key, algorithms=["RS256"], **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 key: Decode key
  452. :type key: str
  453. :param algorithms: Algorithms to use for decoding
  454. :type algorithms: list[str]
  455. :param kwargs: Keyword arguments
  456. :type kwargs: dict
  457. :returns: Decoded token
  458. :rtype: dict
  459. """
  460. return jwt.decode(token, key, algorithms=algorithms, audience=self.client_id, **kwargs)
  461. def load_authorization_config(self, path):
  462. """Load Keycloak settings (authorization).
  463. :param path: settings file (json)
  464. :type path: str
  465. """
  466. with open(path, "r") as fp:
  467. authorization_json = json.load(fp)
  468. self.authorization.load_config(authorization_json)
  469. def get_policies(self, token, method_token_info="introspect", **kwargs):
  470. """Get policies by user token.
  471. :param token: User token
  472. :type token: str
  473. :param method_token_info: Method for token info decoding
  474. :type method_token_info: str
  475. :param kwargs: Additional keyword arguments
  476. :type kwargs: dict
  477. :return: Policies
  478. :rtype: dict
  479. :raises KeycloakAuthorizationConfigError: In case of bad authorization configuration
  480. :raises KeycloakInvalidTokenError: In case of bad token
  481. """
  482. if not self.authorization.policies:
  483. raise KeycloakAuthorizationConfigError(
  484. "Keycloak settings not found. Load Authorization Keycloak settings."
  485. )
  486. token_info = self._token_info(token, method_token_info, **kwargs)
  487. if method_token_info == "introspect" and not token_info["active"]:
  488. raise KeycloakInvalidTokenError("Token expired or invalid.")
  489. user_resources = token_info["resource_access"].get(self.client_id)
  490. if not user_resources:
  491. return None
  492. policies = []
  493. for policy_name, policy in self.authorization.policies.items():
  494. for role in user_resources["roles"]:
  495. if self._build_name_role(role) in policy.roles:
  496. policies.append(policy)
  497. return list(set(policies))
  498. def get_permissions(self, token, method_token_info="introspect", **kwargs):
  499. """Get permission by user token.
  500. :param token: user token
  501. :type token: str
  502. :param method_token_info: Decode token method
  503. :type method_token_info: str
  504. :param kwargs: parameters for decode
  505. :type kwargs: dict
  506. :returns: permissions list
  507. :rtype: list
  508. :raises KeycloakAuthorizationConfigError: In case of bad authorization configuration
  509. :raises KeycloakInvalidTokenError: In case of bad token
  510. """
  511. if not self.authorization.policies:
  512. raise KeycloakAuthorizationConfigError(
  513. "Keycloak settings not found. Load Authorization Keycloak settings."
  514. )
  515. token_info = self._token_info(token, method_token_info, **kwargs)
  516. if method_token_info == "introspect" and not token_info["active"]:
  517. raise KeycloakInvalidTokenError("Token expired or invalid.")
  518. user_resources = token_info["resource_access"].get(self.client_id)
  519. if not user_resources:
  520. return None
  521. permissions = []
  522. for policy_name, policy in self.authorization.policies.items():
  523. for role in user_resources["roles"]:
  524. if self._build_name_role(role) in policy.roles:
  525. permissions += policy.permissions
  526. return list(set(permissions))
  527. def uma_permissions(self, token, permissions=""):
  528. """Get UMA permissions by user token with requested permissions.
  529. The token endpoint is used to retrieve UMA permissions from Keycloak. It can only be
  530. invoked by confidential clients.
  531. http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  532. :param token: user token
  533. :type token: str
  534. :param permissions: list of uma permissions list(resource:scope) requested by the user
  535. :type permissions: str
  536. :returns: Keycloak server response
  537. :rtype: dict
  538. """
  539. permission = build_permission_param(permissions)
  540. params_path = {"realm-name": self.realm_name}
  541. payload = {
  542. "grant_type": "urn:ietf:params:oauth:grant-type:uma-ticket",
  543. "permission": permission,
  544. "response_mode": "permissions",
  545. "audience": self.client_id,
  546. }
  547. self.connection.add_param_headers("Authorization", "Bearer " + token)
  548. data_raw = self.connection.raw_post(URL_TOKEN.format(**params_path), data=payload)
  549. return raise_error_from_response(data_raw, KeycloakPostError)
  550. def has_uma_access(self, token, permissions):
  551. """Determine whether user has uma permissions with specified user token.
  552. :param token: user token
  553. :type token: str
  554. :param permissions: list of uma permissions (resource:scope)
  555. :type permissions: str
  556. :return: Authentication status
  557. :rtype: AuthStatus
  558. :raises KeycloakAuthenticationError: In case of failed authentication
  559. :raises KeycloakPostError: In case of failed request to Keycloak
  560. """
  561. needed = build_permission_param(permissions)
  562. try:
  563. granted = self.uma_permissions(token, permissions)
  564. except (KeycloakPostError, KeycloakAuthenticationError) as e:
  565. if e.response_code == 403: # pragma: no cover
  566. return AuthStatus(
  567. is_logged_in=True, is_authorized=False, missing_permissions=needed
  568. )
  569. elif e.response_code == 401:
  570. return AuthStatus(
  571. is_logged_in=False, is_authorized=False, missing_permissions=needed
  572. )
  573. raise
  574. for resource_struct in granted:
  575. resource = resource_struct["rsname"]
  576. scopes = resource_struct.get("scopes", None)
  577. if not scopes:
  578. needed.discard(resource)
  579. continue
  580. for scope in scopes: # pragma: no cover
  581. needed.discard("{}#{}".format(resource, scope))
  582. return AuthStatus(
  583. is_logged_in=True, is_authorized=len(needed) == 0, missing_permissions=needed
  584. )
  585. def register_client(self, token: str, payload: dict):
  586. """Create a client.
  587. ClientRepresentation:
  588. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  589. :param token: Initial access token
  590. :type token: str
  591. :param payload: ClientRepresentation
  592. :type payload: dict
  593. :return: Client Representation
  594. :rtype: dict
  595. """
  596. params_path = {"realm-name": self.realm_name}
  597. self.connection.add_param_headers("Authorization", "Bearer " + token)
  598. self.connection.add_param_headers("Content-Type", "application/json")
  599. data_raw = self.connection.raw_post(
  600. URL_CLIENT_REGISTRATION.format(**params_path), data=json.dumps(payload)
  601. )
  602. return raise_error_from_response(data_raw, KeycloakPostError)
  603. def device(self):
  604. """Get device authorization grant.
  605. The device endpoint is used to obtain a user code verification and user authentication.
  606. The response contains a device_code, user_code, verification_uri,
  607. verification_uri_complete, expires_in (lifetime in seconds for device_code
  608. and user_code), and polling interval.
  609. Users can either follow the verification_uri and enter the user_code or
  610. follow the verification_uri_complete.
  611. After authenticating with valid credentials, users can obtain tokens using the
  612. "urn:ietf:params:oauth:grant-type:device_code" grant_type and the device_code.
  613. https://auth0.com/docs/get-started/authentication-and-authorization-flow/device-authorization-flow
  614. https://github.com/keycloak/keycloak-community/blob/main/design/oauth2-device-authorization-grant.md#how-to-try-it
  615. :returns: Device Authorization Response
  616. :rtype: dict
  617. """
  618. params_path = {"realm-name": self.realm_name}
  619. payload = {"client_id": self.client_id}
  620. payload = self._add_secret_key(payload)
  621. data_raw = self.connection.raw_post(URL_DEVICE.format(**params_path), data=payload)
  622. return raise_error_from_response(data_raw, KeycloakPostError)
  623. def update_client(self, token: str, client_id: str, payload: dict):
  624. """Update a client.
  625. ClientRepresentation:
  626. https://www.keycloak.org/docs-api/18.0/rest-api/index.html#_clientrepresentation
  627. :param token: registration access token
  628. :type token: str
  629. :param client_id: Keycloak client id
  630. :type client_id: str
  631. :param payload: ClientRepresentation
  632. :type payload: dict
  633. :return: Client Representation
  634. :rtype: dict
  635. """
  636. params_path = {"realm-name": self.realm_name, "client-id": client_id}
  637. self.connection.add_param_headers("Authorization", "Bearer " + token)
  638. self.connection.add_param_headers("Content-Type", "application/json")
  639. # Keycloak complains if the clientId is not set in the payload
  640. if "clientId" not in payload:
  641. payload["clientId"] = client_id
  642. data_raw = self.connection.raw_put(
  643. URL_CLIENT_UPDATE.format(**params_path), data=json.dumps(payload)
  644. )
  645. return raise_error_from_response(data_raw, KeycloakPutError)