Getting 401 error when trying to push data on Firebase realtime database

Hi,
I had a project for which I am using Raspberry Pi Pico W, with the help of which I am trying to push my timestamp on Firebase realtime database when a certain condition is met. Here, when the object temp is in between a predefined range.
Initially, there is no error microcontroller gets connected with Firebase over wifi. I verified it with local ID. The error arises when the object’s temperature is met and it tries to push the timestamp it shows the below error.


Push Response: 401 {
“error” : “Unauthorized request.”
}

Failed to push timestamp to Firebase: 401 {
“error” : “Unauthorized request.”

error mcu

For context the Code that I am using.

1.main.py

import time
import wifi
import firebase
import mlx90614
import led

# Wi-Fi credentials
SSID = 'WIFI NAME'
WIFI_PASSWORD = 'WIFI PASSWORD'

# Firebase credentials
EMAIL = 'EMAIL'
FIREBASE_PASSWORD = 'PASSWORD'

# Main function to run the code
def main():
    # Connect to Wi-Fi
    wifi.connect(SSID, WIFI_PASSWORD)

    # Authenticate with Firebase
    auth_token = firebase.get_auth_token(EMAIL, FIREBASE_PASSWORD)
    if auth_token is None:
        print("Failed to authenticate with Firebase")
        return

    # Define temperature range
    MIN_TEMP = 35
    MAX_TEMP = 37

    # Main loop to continuously monitor temperature and push timestamp if temperature is within range
    last_push_time = 0
    while True:
        try:
            object_temp = mlx90614.read_temp(mlx90614.MLX90614_TOBJ1)
            print("Object Temperature:", object_temp)
            
            if MIN_TEMP <= object_temp <= MAX_TEMP:
                current_time = time.time()
                if current_time - last_push_time >= 30:
                    try:
                        firebase.push_timestamp(current_time, auth_token)
                        led.blink_led(2)  # Blink LED connected to GPIO pin 2
                        last_push_time = current_time
                    except Exception as e:
                        print("Error pushing timestamp to Firebase:", e)
        except Exception as e:
            print("Error reading temperature:", e)
        
        time.sleep(1)  # Adjust the delay according to your requirement

# Run the main function
main()
  1. firebase.py
import urequests as requests
import json

FIREBASE_URL = 'https://heatvison-proximity-default-rtdb.firebaseio.com/time.json'
FIREBASE_API_KEY = 'API_KEY'

def get_auth_token(email, password):
    auth_data = {
        "email": email,
        "password": password,
        "returnSecureToken": True
    }
    auth_response = requests.post(f"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={FIREBASE_API_KEY}", json=auth_data)
    auth_response_data = auth_response.json()
    print("Auth Response:", auth_response_data)  # Debugging line
    if 'idToken' in auth_response_data:
        return auth_response_data['idToken']
    else:
        print("Authentication failed:", auth_response_data)
        return None

def push_timestamp(timestamp, token):
    data = {"timestamp": timestamp}
    headers = {"Content-Type": "application/json", "Authorization": "Bearer " + token}
    response = requests.post(FIREBASE_URL, data=json.dumps(data), headers=headers)
    print("Push Response:", response.status_code, response.text)  # Debugging line
    if response.status_code == 200:
        print("Timestamp pushed to Firebase")
    else:
        print("Failed to push timestamp to Firebase:", response.status_code, response.text)	

Thank you for your time…

1 Like

Hey @Astitva271846, welcome to the forums!

The error “Unauthorized request” typically comes up when there’s an issue with the authorization token so the problem is most likely being caused by your firebase configuration not specifically by your code.

It looks like your using email and password to acquire the token from Firebase. However, these tokens don’t last very long and tend to expire after a certain amount of time for security reasons.

If you think that its possible your tokens are expiring between the time you acquire it and the time you attempt to push the timestamp you may want to obtain a new token before each operation, or at least implement a check to ensure the token is still valid.

You might want to setup your firebase rules to be open (only for testing),

{
  "rules": {
    ".read": "true",
    ".write": "true"
  }
}

This will allow you to confirm if the issue is rule or token related. Definitely change this back after testing.

Other things worthwhile checking:

  • Make sure that you have the correct access privileges set up in your Firebase database.
  • If your Firebase project is in locked mode, you wont be allowed to read or write until you update your rules.
  • Your rules should be least privileged meaning that they only grant access to the data that is needed for your app.
  • Make sure email/password authentication is enabled in the Firebase console. Also ensure your API Key and Firebase URL are correct and they belong to the same Firebase project.

Hope this helps!
Sam

1 Like