I am attempting to setup an APIM endpoint that sends messages to an event hub. I also want to use managed identities in order to authorize the APIM with the event hub. Note that all resources lie in the same subscription. The setup is as follows:
The policy for the operation looks like this:
<policies>
<inbound>
<base />
<authentication-managed-identity resource="https://eventhubs.azure.net" output-token-variable-name="msi-access-token" ignore-error="false" />
<set-header name="Authorization" exists-action="override">
<value>@(String.Concat("Bearer ",(string)context.Variables["msi-access-token"]))</value>
</set-header>
<set-body>{ "Event":"apim-using -aad token", "TrustedService":"AAD" }</set-body>
<set-backend-service base-url="https://[someeventhub].servicebus.windows.net" />
<rewrite-uri template="/input/messages?api-version=2014-01" />
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
Whenever I try to test the operation though, I get a 401 Unauthorized.
HTTP/1.1 401 SubCode=40100: Unauthorized : Unauthorized access for 'Send' operation on endpoint 'sb://[someeventhub].servicebus.windows.net/input/messages?api-version=2014-01'. Tracking Id: [X]
Looking at the trace, the authentication requests looks like it went through okay:
authentication-managed-identity (0.365 ms)
{
"message": "Obtaining managed identity token using clientId:[X] AAD Authority:https://login.windows.net/[A] for https://eventhubs.azure.net audience succeeded.",
"errorResponse": null
}
Am I missing something here? It seems to me that there might be something with an app registration? I don't understand why though - the app already has contributor rights for the subscription. Does it need anything else?
As a final note, the forward request looks like this:
forward-request (0.129 ms)
{
"message": "Request is being forwarded to the backend service. Timeout set to 300 seconds",
"request": {
"method": "POST",
"url": "https://[someeventhub].servicebus.windows.net/input/messages?api-version=2014-01",
"headers": [
{
// A bunch of headers
},
{
"name": "Authorization",
"value": "Bearer [A VALID JWT TOKEN]"
}
]
}
}
the app already has contributor rights for the subscription. Does it need anything else?
Yes; The "Contributor" role gives the app access to the Azure resource management plane for operations like creating a new Event Hub but does not grant access for the data plane.
The app will need to have either "Event Hubs Data sender" or "Event Hubs Data owner" role in order to publish events. (see: Authorize access to Event Hubs resources using Azure Active Directory for more context)