Azure / azure-uamqp-python

AMQP 1.0 client library for Python
MIT License
57 stars 48 forks source link

Improvement on bearer token type support with azure-identity #238

Closed yunhaoling closed 3 years ago

yunhaoling commented 3 years ago

Problem:

If users want to use azure-identity for authenticating the endpoint with uamqp, JWTTokenAuth shall be used, but if the token type is not of jwt, e.g. bearer, then users would need to call update_token by themselves to initially set self.token.

only b'jwt' would be handled internally -- CBSAuthMixin impl.

To improve this, options could be:

  1. CBSAuthMixin could/should call update_token when it's a JWTAuth
  2. Introduce a new BearAuth class

Action items:

  1. Understand the difference between bearer token and jwt token, check if bearer is the same or sub concept of jwt.
  2. Investigate different token types under azure-identity to see if JWTAuth suffices the goal.

Sample code for bearer token type:

from azure.identity import AzureCliCredential
from azure.core.credentials import AccessToken
from uamqp import authentication, SendClient, Message
from uamqp.message import MessageProperties
iothub_uri = '<iot hub name>.azure-devices.net'
credential = AzureCliCredential()
def get_token():
    result = credential.get_token("https://iothubs.azure.net/.default")
    return AccessToken("Bearer " + result.token, result.expires_on)
auth = authentication.JWTTokenAuth(
    audience="https://iothubs.azure.net/.default",
    uri="https://" + iothub_uri,
    get_token=get_token,
    token_type=b'bearer'
)
auth.update_token()  # ****** Manually call update_token
amqp_service_target = "amqps://" + iothub_uri + "/messages/devicebound"
send_client = SendClient(target=amqp_service_target, auth=auth)
msg_props = MessageProperties()
msg_props.to = "/devices/<device id>/messages/devicebound"
message = Message(b'data', msg_props)
send_client.send_message(message)
send_client.close()