How to fix azure.eventhub.exceptions.AuthenticationError: CBS Token authentication failed

Bill LaLonde 50 Reputation points
2023-02-26T03:27:04.21+00:00

I'm attempting to run a sample event generator to familiarize myself with Azure Event Hubs and Azure Stream Analytics.

import asyncio
from azure.eventhub.aio import EventHubProducerClient
from azure.eventhub import EventData

import json
import datetime
import uuid
import random
import time

async def run():
    # Create a producer client to send messages to the event hub.
    # Specify a connection string to your event hubs namespace and
    # the event hub name.
    
    producer = EventHubProducerClient.from_connection_string(conn_str="Endpoint=sb://myNamespace.servicebus.windows.net/;SharedAccessKeyName=EH-ASA-Access;SharedAccessKey=numbersAndLetterAndStuff=", eventhub_name="test_event (myNamespace/test_event)")

    city_list = ["San Franciso", "San Jose", "Los Angesles", "Seattle","Austin", "Dallas", "Denver", "New York", "Atlanta", "Miami", "Phoenix", "Tempe"]
    async with producer:
        for i in range(0, 600):  
            # Create a batch.
            event_data_batch = await producer.create_batch()
            tripdetail1 = {'tripId': str(uuid.uuid4()), 'createdAt': str(datetime.datetime.utcnow()), 'startLocation': random.choice(city_list), 'endLocation': random.choice(city_list), 
            'distance': random.randint(10, 1000), 'fare': random.randint(100, 1000) }
            tripdetail2 = {'tripId': str(uuid.uuid4()), 'createdAt': str(datetime.datetime.utcnow()), 'startLocation': random.choice(city_list), 'endLocation': random.choice(city_list), 
            'distance': random.randint(10, 1000), 'fare': random.randint(100, 1000) }
            tripdetail3 = {'tripId': str(uuid.uuid4()), 'createdAt': str(datetime.datetime.utcnow()), 'startLocation': random.choice(city_list), 'endLocation': random.choice(city_list), 
            'distance': random.randint(10, 1000), 'fare': random.randint(100, 1000) }

            print (tripdetail1);
            print (tripdetail2);
            print (tripdetail3);
            # Add events to the batch.
            event_data_batch.add(EventData(json.dumps(tripdetail1)))
            event_data_batch.add(EventData(json.dumps(tripdetail2)))
            event_data_batch.add(EventData(json.dumps(tripdetail3)))
            event_data_batch.add(EventData(json.dumps(tripdetail1)))


            # Send the batch of events to the event hub.
            await producer.send_batch(event_data_batch)
            time.sleep(1)

loop = asyncio.get_event_loop()
loop.run_until_complete(run())

But when I run the above file from my local machine I get:

\> python .\EventGenerator.py

Traceback (most recent call last):

  File "C:\Users\blalonde\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\eventhub\aio\_client_base_async.py", line 516, in _do_retryable_operation

    return await operation()

  File "C:\Users\blalonde\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\eventhub\aio\_client_base_async.py", line 469, in _open

    while not await self._handler.client_ready_async():

  File "C:\Users\blalonde\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\eventhub\_pyamqp\aio\_client_async.py", line 314, in client_ready_async

    if not await self.auth_complete_async():

  File "C:\Users\blalonde\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\eventhub\_pyamqp\aio\_client_async.py", line 301, in auth_complete_async

    if self._cbs_authenticator and not await self._cbs_authenticator.handle_token():

  File "C:\Users\blalonde\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\eventhub\_pyamqp\aio\_cbs_async.py", line 250, in handle_token

    raise TokenAuthFailure(

azure.eventhub._pyamqp.error.TokenAuthFailure: CBS Token authentication failed.

Status code: None

From what I can tell, I have the SAS Key entered properly, I also did a refresh to make sure it was current. I've checked that my event-name is correct as well. I also tried to use the RootManageSharedAccessKey, but got the same error.

Azure Event Hubs
Azure Event Hubs
An Azure real-time data ingestion service.
591 questions
Azure Stream Analytics
Azure Stream Analytics
An Azure real-time analytics service designed for mission-critical workloads.
342 questions
{count} votes

Accepted answer
  1. Bruno Lucas 4,421 Reputation points MVP
    2023-02-28T08:05:30.8866667+00:00

    Hi Bill LaLonde

    Look like you are on the right track

    that error seems very specific to the token

    We can rule out using the namespace for that type of code where you are pointing to a specific hub

    few things could try:

    1. Secondary connection string
    2. try add the whole connection string including the ";EntityPath=myhub". (I notice at least for triggers it has changed from time to time to have or not the entity. worthy to see if the error change at least)
    3. In the last part, are you adding the hub path name like you have on your example?: , eventhub_name="test_event (myNamespace/test_event)") try change that to , eventhub_name="test_event)") only.
    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Matt Davis 0 Reputation points Microsoft Employee
    2023-03-01T18:30:31.3766667+00:00

    In testing, when I've received the CBS token error - it's been because the EventHub Name is incorrect. I agree with the recommendation above -

    eventhub_name="test_event (myNamespace/test_event)

    should be:

    eventhub_name="test_event"

    0 comments No comments

  2. Mariyam Thomas 20 Reputation points
    2023-11-09T07:01:27.02+00:00

    Make sure that EVENT_HUB_NAME is the name of the event hub and not the Event Hubs namespace. If this value is incorrect, you will receive the error code: CBS Token authentication failed..

    0 comments No comments