Unauthorized error send message from function app to eventgrid with Role Based Access for Event Grid Send - azure

I have a function app with a function that sends message to event grid. A function in this same function app is subscribed to this event grid topic. I get unauthorized access to send message despite function app has set role based access for Event Grid Send.
I have set the function app Identity to System Assigned ON:
I also set the function app Assigned Role to Event Grid Sender at Subscription level (within which the event grid topic also sits):
The event grid sender role assigned is confirmed at IAM Role Assignments of the Event Grid Topic:
When I execute the function app to send data to event grid I get unauthorized error:
//Name of the endpoint of Event grid topic
string topicEndpoint = transformAlgoSendRMessage_TopicEP;
//Creating client to publish events to eventgrid topic
EventGridPublisherClient client = new EventGridPublisherClient(new Uri(topicEndpoint), new DefaultAzureCredential());
//Creating a sample event with Subject, Eventtype, dataVersion and data
EventGridEvent egEvent = new EventGridEvent("TransformTelemetry", "TransformAlgorithm.broadcastTransform", "1.0", machinePartTransformTelemetry);
// Send the event
try
{
await client.SendEventAsync(egEvent);
if (b_debug_contractor)
log.LogInformation("SendRTransformMessage sent transformdata - PosX:" + machinePartTransformTelemetry[1]);
}
catch (Exception e)
{
log.LogError("Failed to send SendRTransformMessage. " + e.Message);
}
Unauthorized Error:
[2022-11-25T08:00:45.646Z] Failed to send SendRTransformMessage. The principal associated with access token presented with the incoming request does not have permission to send data to /subscriptions/MySubscriptionID/resourceGroups/myresourcegroup/providers/Microsoft.EventGrid/topics/functionappname. Report 'e9595a36-8420-4466-b91a-801fbfcf605d:4:11/25/2022 8:00:48 AM (UTC)' to our forums for assistance or raise a support ticket.
[2022-11-25T08:00:45.646Z] Status: 401 (The principal associated with access token presented with the incoming request does not have permission to send data to /subscriptions/mySubscriptionID/resourceGroups/myresourcegroup/providers/Microsoft.EventGrid/topics/myfunctionappname. Report 'e9595a36-8420-4466-b91a-801fbfcf605d:4:11/25/2022 8:00:48 AM (UTC)' to our forums for assistance or raise a support ticket.)
[2022-11-25T08:00:45.647Z] ErrorCode: Unauthorized
[2022-11-25T08:00:45.647Z]
[2022-11-25T08:00:45.647Z] Content:
[2022-11-25T08:00:45.648Z] {
[2022-11-25T08:00:45.648Z] "error": {
[2022-11-25T08:00:45.649Z] "code": "Unauthorized",
[2022-11-25T08:00:45.649Z] "message": "The principal associated with access token presented with the incoming request does not have permission to send data to /subscriptions/mySubscriptionID/resourceGroups/myresourcegroup/providers/Microsoft.EventGrid/topics/myfunctionappname. Report 'e9595a36-8420-4466-b91a-801fbfcf605d:4:11/25/2022 8:00:48 AM (UTC)' to our forums for assistance or raise a support ticket.",
[2022-11-25T08:00:45.650Z] "details": [{
[2022-11-25T08:00:45.650Z] "code": "Unauthorized",
[2022-11-25T08:00:45.650Z] "message": "The principal associated with access token presented with the incoming request does not have permission to send data to /subscriptions/mySubscriptionID/resourceGroups/myresourcegroup/providers/Microsoft.EventGrid/topics/myfunctionappname. Report 'e9595a36-8420-4466-b91a-801fbfcf605d:4:11/25/2022 8:00:48 AM (UTC)' to our forums for assistance or raise a support ticket."
I note I tried with key credentials but the Azure would not recognize the key.

I tried to reproduce the same in my environment and got below results
I created one function app and enabled system assigned identity as below:
Add role assignment to the Event grid like below: Go to Azure Portal -> Event grid Topics -> Your Topic -> Access control (IAM)
The error 401 Unauthorized may occur if you selected service principal instead of managed identity where 'Type' is App not Function App while assigning role like below:
To resolve the error, make sure to select Managed Identity as Function App while assigning role to Event grid like below:
Select Review+assign to assign the role as below:
Role EventGrid Data Sender got assigned successfully to the Event grid like below:
This will automatically reflect in the function app too and no need to assign this role separately to function app identity.
To confirm that, Go to Azure Portal -> Your Function App -> Identity -> Azure role assignments
Now restart the function app and execute the function again. If the issue still persists, raise a support ticket.
Reference:
Send Events To Event Grid Topic Using Managed Service Identity by Rittik Basu

Related

Unauthorized access. 'Send' claim(s) are required to perform this operation - Azure Queue Send Message

We have been trying to send a test message to Azure Service Bus Queue from SPFx webpart, however, every time we are seeing --> Unauthorized access. 'Send' claim(s) are required to perform this operation. Resource: 'sb://.servicebus.windows.net/'.
Steps we have followed -
Created a sample SPFx webpart.
Used
{
"resource": "Microsoft.ServiceBus",
"scope": "user_impersonation"
}
inside webApiPermissionRequests of package-solution.json.
Deployed the webpart and approved scopes from Admin center so that an Azure AD App service principal gets created with API Permissions.
Now migrated the Redirect Uris to SPA for PKCE flow (MSAL 2.0).
Set Allow Public Client Flows to "Yes".
Then got the client id and tenant id from AD App and used in our SPFx solution to connect Service Bus Queue through javascript SDK.
Used InteractiveBrowserCredential from #azure/identity and ServiceBusClient from #azure/service-bus to send a message to the Queue. Snippet below -
try{
const credential = new InteractiveBrowserCredential({
tenantId: "<tenant-id>",
clientId: "<SharePoint Online Client Extensibility Web Application Principal client-id>"
});
const fullyQualifiedNamespace = "<servicebus-namespace>.servicebus.windows.net";
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
const sender = serviceBusClient.createSender("queue-name");
await sender.sendMessages({body: "test"});
console.log("message sent");
}
catch(error){
console.log(error);
}
Provided Owner and Azure Service Bus Data Owner access from IAM to the Service Principal. Both queue and service bus level.
However, every time code block is throwing exception and the message is - Unauthorized access. 'Send' claim(s) are required to perform this operation. Resource: 'sb://.servicebus.windows.net/'.
Any help would be appreciated. Thanks !!

MS graph api: Subscribe for notifications on groups changes with Azure event hub

basically I am trying to subscribe for notifications on group changes in order to adjust authorizations in a 3rd party system, find the code below. It uses the graph sdk for Java. I have added the documentation I followed for reference, see Change notification delivery and post subscriptions in Microsoft Docs.
Unfortunately I get a
Invalid event hub notification url. I tried both domain and tenant id, no luck. It doesn't really surprise me as the notificationUrl really seems odd. Can anyone share some light in here?
// From https://learn.microsoft.com/de-de/graph/change-notifications-delivery:
// The main difference during subscription creation will be the notificationUrl. You must set it to
// EventHub:https://<azurekeyvaultname>.vault.azure.net/secrets/<secretname>?tenantId=<domainname>, with the following values:
// azurekeyvaultname - The name you gave to the key vault when you created it. Can be found in the DNS name.
// secretname - The name you gave to the secret when you created it. Can be found on the Azure Key Vault Secrets page.
// domainname - The name of your tenant; for example, consto.onmicrosoft.com or contoso.com. Because this domain will be used to access the Azure Key Vault, it is important that it matches the domain used by the Azure subscription that holds the Azure Key Vault. To get this information, you can go to the overview page of the Azure Key Vault you created and click the subscription. The domain name is displayed under the Directory field.
#GetMapping("/subscribe")
public void subscribeTochangeNotifications() {
// following https://learn.microsoft.com/en-us/graph/api/subscription-post-subscriptions?view=graph-rest-1.0&tabs=http#request-example
Subscription subscription = new Subscription();
subscription.changeType = "created,updated";
subscription.notificationUrl = "EventHub:https://xxxxxxxxx.vault.azure.net/secrets/event-hub-client-secret?tenantId=xxxxxxxxx-xxxx-xxxx-xxxxxxxxx";
subscription.expirationDateTime = OffsetDateTime.parse("2022-07-05T18:23:45.9356913Z");
subscription.resource = "/groups";
subscription.clientState = "SecretClientState";
azureClient.subscriptions().buildRequest().post(subscription);
}
Detailed error message is:
nested exception is com.microsoft.graph.http.GraphServiceException: Error code: InvalidRequest
Error message: Invalid event hub notification url='EventHub:https://xxxxxxxxxxxxxxxxx.vault.azure.net/secrets/event-hub-client-secret?tenantId=yyyyyyy-yyy-yyyy-yyyyyyyyyy'.
POST https://graph.microsoft.com/v1.0/subscriptions
SdkVersion : graph-java/v5.30.0
SdkVersion : graph-java/v5.30.0
[...]
400 : Bad Request
[...]
we ran into the same issue (setup with pulumi). Our connection string in the key vault secret was missing the
";EntityPath=graphevents"
at the end.

Azure B2C: Webhook Notifications of User Activity Aren't Being Picked Up

Due to an issue that I've been dealing with Azure B2C, I was thinking of using notification webhooks to receive information on when a user was created/updated.
While I'm able to create a subscription to the users resource, the webhook won't fire off when I actually create/update a user via the Graph API.
I created the subscription as follows:
POST https://graph.microsoft.com/v1.0/subscriptions
{
"changeType":"updated",
"notificationUrl":"https://a7500b01de1c.ngrok.io/b2chook/Users",
"resource":"users",
"expirationDateTime":"2021-08-09T01:50:17.699528+00:00"
}
The webhook that's listening into the subscription is being done in Python via Flask.
Here's the current code that's written up to receive the webhook notification:
class B2CUserHook(Resource):
#staticmethod
def post():
logger.debug(f"Microsoft Graph API notified the endpoint!")
if "validationToken" in request.args:
token = request.args.get('validationToken')
#res = make_response(token, 201)
#res.mimetype = "text/plain"
logger.debug(f"Token to return back to Graph API: {token}")
return Response(token, mimetype="text/plain")
return Response(status=202)
With the url being declared as a resource:
api.add_resource(user_controller.B2CUserHook, "/b2chook/Users")
So, how exactly can I fix this issue so that I can receive the notification?
It says it in the linked document:
Azure AD B2C tenants are not supported

Create subscription for Sharepoint List returns 403 forbidden

I'm using Microsoft Graph API to fetch items from Sharepoint list. Everything has worked well and I have a token, which works for getting items from the list
Now I want to get a notice, when any item gets updated on that list. For that, I tried to create webhook with subscription with the same token. However when trying to create subscription, the API returns 403.
var subscription = new Subscription
{
Resource = "sites/{siteId}/lists/{listId}/",
NotificationUrl = "{notification url}",
ExpirationDateTime = DateTimeOffset.Now.AddDays(2),
ChangeType = "updated"
};
var res = await graphServiceClient.Subscriptions
.Request()
.AddAsync(subscription);
I have set the required Sites.ReadWrite.All permission to my app registration. The call to the API returns me
{
Error: Code: ExtensionError
Message: Operation: Create; Exception: [Status Code: Forbidden; Reason: Access denied. You do not have permission to perform this action or access this resource.]
Inner error:
AdditionalData:
request-id: 99445d24-8d09-45a5-98e7-05b99587fd7f
date: 2020-04-26T21:53:21
ClientRequestId: 99445d24-8d09-45a5-98e7-05b99587fd7f
}
Am I targeting wrong resource or is there any other permission, that app needs?
Edit: also tried using certificate to authorize, still nothing.
For creating a new webhook subscription, the application must have at least edit permissions to the SharePoint list where the subscription will be created (if the App is Azure AD). If the application is a SharePoint Add-in, You must grant 'Manage' or higher permission.

Can I create an event grid subscription to an Azure function app before the function is published?

I have been trying to create an event grid subscription to an Event Grid Trigger function which is created to capture Blob storage events, using ARM templates. I successfully create the function app resource first, then try to create the event grid subscription on the created function app, but it fails with the following error:
"error": {
"code": "ResourceDeploymentFailure",
"message": "The resource operation completed with terminal provisioning state 'Failed'.",
"details": [
{
"code": "Url validation",
"message": "The attempt to validate the provided endpoint https://myfunction.azurewebsites.net/runtime/webhooks/eventgrid failed. For more details, visit https://aka.ms/esvalidation."
}
]
}
Here I have used webhook URL as the endpoint. I've come to know that there is a validation call that goes back to the function app to verify its existence.
My question is, do we need to publish the Event Grid Trigger function to the function app before trying to create an event grid subscription for that?
P.S. I have also tried the same order with AzureFunction as the endpoint type (2020-01-01 version), but it still failed to create the subscription.
Based on the validation details described here:
At the time of event subscription creation/update, Event Grid posts a subscription validation event to the target endpoint
as a workaround, you can use a dummy (nop operation) subscriber handler endpoint for creating your subscription and then update a webhook endpoint with your real subscriber handler endpoint.

Resources