The code looks good itself - can you include some logging/printing in your testing to validate that the refresh_token() code is being ran and a new access token is being created? You can also validate that the new access token works through Postman or through the devHub API Reference found here - This is a guide that shows you how to use the "Try It" feature https://developer.arubanetworks.com/aruba-central/docs/api-reference-guide
Original Message:
Sent: Jul 10, 2024 08:47 PM
From: bcarreno
Subject: token refresh api aruba central
Do you see anything missing in the code to refresh the token?
import requestsfrom datetime import datetime, timedelta# Variables globales para el token de acceso y su expiraciónaccess_token = "vpV4fyJ2JxvwlSNa77aVxxxxxxxxxx"refresh_token_str = "bk7ylHeIzHYxxxxxxxxxxxxxxxxxx"token_expiry = datetime.now() + timedelta(seconds=7200) # Asumiendo 7200 segundos como tiempo de expiración# Configuración de los datosbase_url = "https://apigw-uswest4.central.arubanetworks.com"client_id = "OjJtmLDpJNObhkuGIxxxxxxxxxxxxxx"client_secret = "7MCSnUX4NMXVGLTM8xxxxxxxxxxx"portal_id = "bcc1fb6a-956c-4074xxxxxxxxxxxxxxx"# Función para refrescar el tokendef refresh_token(base_url, client_id, client_secret, refresh_token): global access_token, token_expiry # Declarar que estas son variables globales url = f"{base_url}/oauth2/token" payload = { "client_id": client_id, "client_secret": client_secret, "grant_type": "refresh_token", "refresh_token": refresh_token } response = requests.post(url, data=payload) if response.status_code == 200: token_info = response.json() access_token = token_info['access_token'] token_expiry = datetime.now() + timedelta(seconds=token_info['expires_in']) return token_info else: response.raise_for_status()# Función para verificar y actualizar el token si es necesariodef ensure_valid_token(): global access_token, token_expiry # Declarar que estas son variables globales if datetime.now() >= token_expiry: refresh_token(base_url, client_id, client_secret, refresh_token_str)# Función para crear un nuevo visitantedef create_guest_visitor(base_url, token, portal_id, visitor_data): url = f"{base_url}/guest/v1/portals/{portal_id}/visitors" headers = { "Authorization": f"Bearer {token}", "Content-Type": "application/json" } response = requests.post(url, headers=headers, json=visitor_data) if response.status_code == 200 or response.status_code == 201: return response.json() else: response.raise_for_status()# Datos del visitantevisitor_data = { "name": "hmarin", "user": { "phone": None, "email": "bruce.carreno@xxxx.com" }, "is_enabled": True, "valid_till_days": 1, "notify": True, "notify_to": "email", "password": "secret-passwd123"}# Asegurarse de que el token es válido y luego crear el visitantetry: ensure_valid_token() # Verificar y actualizar el token si es necesario visitor_response = create_guest_visitor(base_url, access_token, portal_id, visitor_data) print(f"Visitor created successfully: {visitor_response}")except requests.exceptions.HTTPError as e: print(f"Error creating guest visitor: {e}") print(f"Response text: {e.response.text}") print("There was an error creating the guest visitor. Please try again later.")

Original Message:
Sent: Jul 10, 2024 01:57 PM
From: schmelzle
Subject: token refresh api aruba central
> So, can I refresh the same token that I have created?
Yes, that is the purpose of the refresh token. To refresh the access token to a new value instead of creating a new access token each time.
Original Message:
Sent: Jul 10, 2024 01:46 PM
From: bcarreno
Subject: token refresh api aruba central
So, can I refresh the same token that I have created?
Or will a new token appear in the list each time I perform a refresh?

Original Message:
Sent: Jul 10, 2024 01:19 PM
From: schmelzle
Subject: token refresh api aruba central
No, it is not possible to change the expiry time for access tokens. They expire in 2 hours (source).
Original Message:
Sent: Jul 09, 2024 04:43 PM
From: bcarreno
Subject: token refresh api aruba central
Hi,
Is it possible for the access token to last longer, ideally one year? I am trying to have the token update automatically when it expires, but this question came up.
Test code not working
import requestsimport loggingfrom datetime import datetime, timedelta# Configuración del loggerdef console_logger(name, level="DEBUG"): logger = logging.getLogger(name) logger.setLevel(level) handler = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) return loggerlogger = console_logger(__name__)# Variables globales para el token de acceso y su expiraciónaccess_token = Nonetoken_expiry = None# Configuración de los datosbase_url = "https://api.central.arubanetworks.com"client_id = "your_client_id"client_secret = "your_client_secret"refresh_token_str = "your_refresh_token"portal_id = "your_portal_id"# Función para refrescar el tokendef refresh_token(base_url, client_id, client_secret, refresh_token): url = f"{base_url}/oauth2/token" payload = { "client_id": client_id, "client_secret": client_secret, "grant_type": "refresh_token", "refresh_token": refresh_token } response = requests.post(url, data=payload) if response.status_code == 200: token_info = response.json() global access_token, token_expiry access_token = token_info['access_token'] # Calculamos el tiempo de expiración (asumiendo 1 hora de validez) token_expiry = datetime.now() + timedelta(seconds=token_info['expires_in']) logger.info("Token refreshed successfully") return token_info else: logger.error("Failed to refresh token: %s", response.text) response.raise_for_status()# Función para verificar y actualizar el token si es necesariodef ensure_valid_token(): global access_token, token_expiry if access_token is None or datetime.now() >= token_expiry: refresh_token(base_url, client_id, client_secret, refresh_token_str)# Función para crear un nuevo visitantedef create_guest_visitor(base_url, token, portal_id, visitor_data): url = f"{base_url}/guest/v1/portals/{portal_id}/visitors" headers = { "Authorization": f"Bearer {token}", "Content-Type": "application/json" } response = requests.post(url, headers=headers, json=visitor_data) if response.status_code == 200 or response.status_code == 201: return response.json() else: logger.error("Failed to create guest visitor: %s", response.text) response.raise_for_status()