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

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

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 !!

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

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

The Azure Alerts using webhook to Slack is not working

I'm using Azure Alerts to use webhooks. I added the webhook in the action group. The URL I used is the one from Slack.
I also added a Notification Type Email. The notification email gets triggered but I am not receiving any message in the Slack channel.
I was able to push messages to the webhooks using postman hence I know my webhook is correct. But Azure Alert is not able to trigger the webhook. I am not receiving any messages in the Slack channel.
Azure Monitor sends a notification with its own schema definition. Slack doesn't recognize it, so you cannot see any notifications in the channel. It is possible to create a Logic App or Azure Function to transform the default schema.
Here the more information about it:
https://learn.microsoft.com/en-us/azure/azure-monitor/alerts/alerts-common-schema
Slack expect a json object when using webhooks. When sending directly from azure alert you will get bad request.
Every slack channel has an e-mail adress. You can post messages to the channel using that email in azure alerts
Anyone looking for using Slack and Azure Alerts. This seems to work fine:
...
webhook_receiver {
name = "Slack"
service_uri = "https://hooks.slack.com/services/secret"
use_common_alert_schema = false
}
Then in the scheduled query rules alert:
...
action {
action_group = [data.azurerm_monitor_action_group.actiongroup.id]
email_subject = "Disk storage at less than 10%"
custom_webhook_payload = "{ \"text\" : \"Warning: Storage has less than 10% diskspace remaining!\"}"
}

Make use of the gmail api through a service account from the server side avoiding the OAUTH2 GUI

I have an application developed in python that uses the SMPT service to connect to a gmail account. This type of connection is typified as an "Access of insecure applications" lesssecureapps.
To remedy this I have set myself the task of updating my app, using the gmail api and for authentication to use a private key generated from a service account (without using G-Suit).
I have created a first proof of concept and it seems that it connects and authenticates correctly, but when trying to get the labels of the gmail account I get the following message:
<HttpError 400 when requesting https://gmail.googleapis.com/gmail/v1/users/me/labels?alt=json returned "Precondition check failed.">
I recap the steps I have followed to configure my google account:
I access Google Api Console and enable the use of the gmail api through the button that appears at the top: Enable apis and services
I access the credentials section, click on the top button: "create credentials" and select Service account
I create a service account and then generate a private key in json format
I add a small code snippet with my proof of concept and it that returns the error that I comment on the top:
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ['https://mail.google.com/','https://www.googleapis.com/auth/gmail.modify','https://www.googleapis.com/auth/gmail.readonly','https://www.googleapis.com/auth/gmail.labels','https://www.googleapis.com/auth/gmail.metadata','https://www.googleapis.com/auth/gmail.addons.current.message.metadata','https://www.googleapis.com/auth/gmail.addons.current.message.readonly']
SERVICE_ACCOUNT_FILE = '/home/user/keys/privatekey_from_service_account.json'
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('gmail', 'v1', credentials=credentials)
# Call the Gmail API
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
if not labels:
print('No tienes labels.')
else:
print('Labels:')
for label in labels:
print(label['name'])
How can I solve my problem without using g-suite?
"Precondition check failed."
Means that you are not allowed to do what you are trying to do.
use a private key generated from a service account (without using G-Suit).
The Gmail api does not support service accounts for non gsuite domains. You can only use a service account with a Gsuite domain account and gsuite domain emails.
Services account wont work with normal google gmail accounts.

Azure AD OpenIDConnect + ASP.NET Core - Authenticate and Extra Permissions/Token?

I am using the following bits against my Azure AD to authenticate with ASP.NET Core.
https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-webapp-openidconnect-aspnetcore/
https://github.com/Azure-Samples/active-directory-dotnet-webapp-openidconnect-aspnetcore
I have the basic login/auth working after creating an Azure AD app. User can login/logout.
My question is given this, what's the best way when a user Auth's to log to a DB? I thought about making the redirect URL to an endpoint, saving, then just redirecting back to "Home" but is that ideal?
Also, is it possible to retrieve a bearer token via this approach? Or does this require another type of call or extending "scope"? So that for example I could retrieve the authenticated users Manager.
https://graph.microsoft.com/v1.0/me/manager
My question is given this, what's the best way when a user Auth's to log to a DB? I thought about making the redirect URL to an endpoint, saving, then just redirecting back to "Home" but is that ideal?
This way only able to log those who already sign-in your app successfully. It is not able to log those users who are attempt to sign-in your app but enter the wrong password.
Azure AD already provide lots of report to gain visibility into the integrity and security of your organization’s directory.( refer here)
And if you are using the Azure AD Premium, you can review the sign-in activities via the Azure new portal below:
And if you want to store the sign-in activity in your web app, you can write the custom code after the token is verified. Here is the code for your reference:
// Configure the OWIN pipeline to use OpenID Connect auth.
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
ClientId = Configuration["AzureAD:ClientId"],
Authority = String.Format(Configuration["AzureAd:AadInstance"], Configuration["AzureAd:Tenant"]),
ResponseType = OpenIdConnectResponseType.IdToken,
PostLogoutRedirectUri = Configuration["AzureAd:PostLogoutRedirectUri"],
Events = new OpenIdConnectEvents
{
OnRemoteFailure = OnAuthenticationFailed,
OnTokenValidated = context => {
//write the custom code to store users login-in
return Task.FromResult(0); }
},
});
Also, is it possible to retrieve a bearer token via this approach?
Yes. We can get the token after receive the authorization code. You can refer the code sample here to acquire the token from asp.net core app.

Resources