Authorization error on external Service

Greetings,

I have been trying to add Home Assistant as an external service to Open Remote, which by the looks of it, it worked. However, most of the actions rises a problem with not being authorized to do them, even if every time I access it I use my login credentials from Open Remote. Does anyone know if its a thing from the browser, or my code?
I have prepared a file to prepare the connection, which is:

import os
import time
import requests
import logging
import urllib3


urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

#  Logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("OR-Service-Bridge")


OPENREMOTE_HOST = "https://192.168.191.70"  # URL
REALM = "master"
CLIENT_ID = "exitos_ha_2"                   #  Service User
CLIENT_SECRET = "XXXXXXXXXXXXXXXXXX"

SERVICE_ID = "exitos_ha_dashboard"
SERVICE_LABEL = "Home Assistant"
SERVICE_ICON = "mdi-home-assistant"
HOMEPAGE_URL = "http://192.168.191.252:8123/app/8e15d424_exitos"

def get_token():
    url = f"{OPENREMOTE_HOST}/auth/realms/{REALM}/protocol/openid-connect/token"
    payload = {
        "grant_type": "client_credentials",
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET
    }
    try:
        response = requests.post(url, data=payload, verify=False, timeout=10)
        response.raise_for_status()
        return response.json().get("access_token")
    except Exception as e:
        logger.error(f"Error token OpenRemote (revisa credencials): {e}")
        return None

def register_service(token):
    url = f"{OPENREMOTE_HOST}/api/{REALM}/service"
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    payload = {
        "serviceId": SERVICE_ID,
        "label": SERVICE_LABEL,
        "icon": SERVICE_ICON,
        "homepageUrl": HOMEPAGE_URL,
        "status": "AVAILABLE"
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers, verify=False, timeout=10)
        response.raise_for_status()
        data = response.json()
        instance_id = data.get("instanceId")
        logger.info(f"  Registered to OpenRemote! Instance ID: {instance_id}")
        return instance_id
    except Exception as e:
        logger.error(f"Error: {e}")
        if 'response' in locals() and hasattr(response, 'text'):
            logger.error(f"Detaills: {response.text}")
        return None

def send_heartbeat(token, instance_id):
    url = f"{OPENREMOTE_HOST}/api/{REALM}/service/{SERVICE_ID}/{instance_id}"
    headers = {
        "Authorization": f"Bearer {token}",
    }
    try:
        response = requests.put(url, headers=headers, verify=False, timeout=10)
        response.raise_for_status()
        logger.info(" Heartbeat sent.")
        return True
    except Exception as e:
        logger.warning(f"Error with Heartbeat.: {e}")
        return False

def main():
    instance_id = None
    
    while True:
        if not instance_id:
            token = get_token()
            if token:
                instance_id = register_service(token)
                if not instance_id:
                    time.sleep(15)  # try again
                    continue
            else:
                time.sleep(15)
                continue
                
        # Heartbeat loop
        if instance_id:
            time.sleep(30) 
           
            token = get_token()
            if not token or not send_heartbeat(token, instance_id):
                instance_id = None 

if __name__ == "__main__":
    time.sleep(5)
    main()

Hi!

This sounds like a problem specific to Home Assistant with the URL you are using.
You can check your browser logs to see what is actually happening in the background.
It might be that Home Assistant requires a “redirect to the login page”,
but might not redirect within this window.

1 Like

What actually makes me wonder is how is it possible that I can access any functionality from “base” Home Assistant, but the moment I try to use any kind of extension / addon this problem occurs.

I will be looking at your advice, thanks!