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:
- I have an APIM instance with a system assigned identity. This identity has been giving the contributor role on a subscription level.
- I have an event hub namespace and event hub, which is setup to receive the events.
- I have created an API + operation, that generates events, based on the payload and sends them to the event hub. The example below just sends some hardcoded body, I want to get it working before working on the payload.
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]"
}
]
}
}