Developer

 View Only
last person joined: 9 days ago 

Expand all | Collapse all

token refresh api aruba central

This thread has been viewed 32 times
  • 1.  token refresh api aruba central

    Posted Jul 09, 2024 04:43 PM

    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 requests
    import logging
    from datetime import datetime, timedelta
    
    # Configuración del logger
    def 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 logger
    
    logger = console_logger(__name__)
    
    # Variables globales para el token de acceso y su expiración
    access_token = None
    token_expiry = None
    
    # Configuración de los datos
    base_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 token
    def 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 necesario
    def 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 visitante
    def 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()


  • 2.  RE: token refresh api aruba central

    MVP GURU
    Posted Jul 10, 2024 08:02 AM

    Hi,

    the code look good, what error do you have when try to renew token ?

    In my code (with PowerShell) i don't POST the payload but pass by parameter (i don't known if there is a different for this API call)

    https://github.com/PowerAruba/PowerArubaCL/blob/master/PowerArubaCL/Private/Token.ps1#L16



    ------------------------------
    PowerArubaSW : Powershell Module to use Aruba Switch API for Vlan, VlanPorts, LACP, LLDP...

    PowerArubaCP: Powershell Module to use ClearPass API (create NAD, Guest...)

    PowerArubaCL: Powershell Module to use Aruba Central

    PowerArubaCX: Powershell Module to use ArubaCX API (get interface/vlan/ports info)..

    ACEP / ACMX #107 / ACDX #1281
    ------------------------------



  • 3.  RE: token refresh api aruba central

    EMPLOYEE
    Posted Jul 10, 2024 01:19 PM

    No, it is not possible to change the expiry time for access tokens. They expire in 2 hours (source).




  • 4.  RE: token refresh api aruba central

    Posted Jul 10, 2024 01:47 PM

    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?




  • 5.  RE: token refresh api aruba central

    EMPLOYEE
    Posted Jul 10, 2024 01:57 PM

    > 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.




  • 6.  RE: token refresh api aruba central

    Posted Jul 10, 2024 08:47 PM

    Do you see anything missing in the code to refresh the token?

    import requests
    from datetime import datetime, timedelta
    
    # Variables globales para el token de acceso y su expiración
    access_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 datos
    base_url = "https://apigw-uswest4.central.arubanetworks.com"
    client_id = "OjJtmLDpJNObhkuGIxxxxxxxxxxxxxx"
    client_secret = "7MCSnUX4NMXVGLTM8xxxxxxxxxxx"
    portal_id = "bcc1fb6a-956c-4074xxxxxxxxxxxxxxx"
    
    # Función para refrescar el token
    def 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 necesario
    def 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 visitante
    def 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 visitante
    visitor_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 visitante
    try:
        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.")




  • 7.  RE: token refresh api aruba central

    Posted Jul 11, 2024 06:28 PM

    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 



    ------------------------------
    Ti Chiapuzio-Wong (they/them)
    HPE Aruba Networking
    ------------------------------



  • 8.  RE: token refresh api aruba central

    Posted Jul 17, 2024 04:55 AM

    You can use pycentral to automate this for you. Or you just peak into source code of pycentral to see, what is going on.

    Best, Gorazd



    ------------------------------
    Gorazd Kikelj
    MVP Guru 2024
    ------------------------------



  • 9.  RE: token refresh api aruba central

    EMPLOYEE
    Posted 22 days ago

    Hi @bcarreno,

    I reviewed your code and noticed that the new access & refresh tokens aren't saved in the refresh_token function. While the global variables gets updated initially, the script will stop working when you run it again as it has invalid access & refresh token in the script. It's better to store token details (access token, refresh token, etc.) in a file outside the script. You should update the access & refresh tokens in the file whenever you generate or refresh a token.

    As @GorazdKikelj mentioned, consider using the PyCentral Python package, which handles token management and simplifies your automation scripts. Check out this Aruba Developer Hub page to get started with PyCentral.