Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

49 rader
1.5 KiB

  1. import time
  2. import requests
  3. class TokenManager:
  4. def __init__(self, token_url: str, client_id: str, client_secret: str,
  5. username: str, password: str, audience: str | None = None,
  6. verify_tls: bool = True, timeout_s: float = 10.0):
  7. self.token_url = token_url
  8. self.client_id = client_id
  9. self.client_secret = client_secret
  10. self.username = username
  11. self.password = password
  12. self.audience = audience
  13. self.verify_tls = verify_tls
  14. self.timeout_s = float(timeout_s)
  15. self._token: str | None = None
  16. self._exp: int = 0 # epoch seconds
  17. def get_token(self) -> str:
  18. now = int(time.time())
  19. if self._token and now < (self._exp - 30):
  20. return self._token
  21. data = {
  22. "grant_type": "password",
  23. "client_id": self.client_id,
  24. "client_secret": self.client_secret,
  25. "username": self.username,
  26. "password": self.password,
  27. }
  28. if self.audience:
  29. data["audience"] = self.audience
  30. r = requests.post(
  31. self.token_url,
  32. data=data,
  33. headers={"Content-Type": "application/x-www-form-urlencoded"},
  34. timeout=self.timeout_s,
  35. verify=self.verify_tls,
  36. )
  37. r.raise_for_status()
  38. payload = r.json()
  39. token = payload["access_token"]
  40. expires_in = int(payload.get("expires_in", 60))
  41. self._token = token
  42. self._exp = now + expires_in
  43. return token