how to add headers in the httpresponse trigger

Naruto 61 Reputation points
2021-01-20T20:42:54.82+00:00

I have created the azure function and the app is successfully registered, add authentication to the function app. Now if hit the URL using postman I have the option of passing a token before hitting the URL. But want I want to do is automate the authentication part from code that gets token and verifies it. Sharing my code below.

def authenticate_client_key():
    authority_host_uri = 'https://login.microsoftonline.com'
    tenant = '<tenantid>'
    authority_uri = authority_host_uri + '/' + tenant
    resource_uri = 'https://management.core.windows.net/'
    client_id = '<clientid'
    client_secret = '<clientsecret>'
    context = adal.AuthenticationContext(authority_uri, api_version=None)
    mgmt_token = context.acquire_token_with_client_credentials(resource_uri, client_id, client_secret)
    credentials = AADTokenCredentials(mgmt_token, client_id)
    return credentials

here credentials is of type dict, from which I create a header - {"Authorization":"Bearer {}".format(bearer_token)}.
this header needs to added to the req object in the main method of function app.

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

inside this req object

  • I tried adding req.update(headers=credentials) but failed
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,131 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
22,172 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Pramod Valavala 20,636 Reputation points Microsoft Employee
    2021-01-22T14:27:44.247+00:00

    In a client application, the dictionary you've mentioned would be correct. For example, if you are using the requests package, code like this would be what you need

       requests.post(url, data = dataobj, headers = {"Authorization":"Bearer {}".format(bearer_token)})  
    

    In your Azure Function, the req (instance of HttpRequest) object has a headers property to access a header value, like below

       req.headers.get('authorization')  
    

    You can read more about the HTTP Binding in Python here.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.