I have a SPA, and I am trying to send a message on behalf of a user in Teams via -
POST https://graph.microsoft.com/v1.0/teams/{teamid}/channel/{channelid}/messages
through the same.
But I am continuously getting this error -
{
"error": {
"code": "Unauthorized",
"message": "Unauthorized",
"innerError": {
"date": "2020-12-03T06:09:02",
"request-id": "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"client-request-id": "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"
}
}
}
The SPA is build using Azure AD App registrations and the Following API permissions have been given to the app :
ChannelMessage.Send (Delegate) , Chat.ReadWrite (Delegate), ChatMessage.Send (Delegate).
The above API works when calling from the Microsoft Graph explorer portal.
I also compared the access token on jwt.io from both Graph Explorer and My Azure AD application and both have the scopes -
[ ChannelMessage.Send ] which is required to send a message to a channel
Need help on this if I have missed something out or if I am doing something wrong.
Posting a message to channel using Send Channel Message Graph API requires ChannelMessage.Send Group.ReadWrite.All permissions
Here is the code snippet for sending messages to channel, you need to implement authProvider to pass it graphClient, I tested it for my tenant and I was succesfully able to send message in Channel.
Below is Code snippet
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var chatMessage = new ChatMessage
{
Body = new ItemBody
{
Content = "Hello World"
}
};
await graphClient.Teams["{TeamId}"].Channels["{ChannelId}"].Messages
.Request()
.AddAsync(chatMessage);
I'm not an expert on this, but I think you can't connect directly from an untrusted client (i.e. a SPA) to the Graph directly, and that you'd first need to get an "on behalf of" token (which means you'd need to have your own backend API to make a secure connection and retrieve this token). You can see a sample for this (dotnet and node) over here: https://github.com/HiltonGiesenow/teams-dev-samples/tree/add-tabs-sso-sample
Related
I'm using Microsoft Graph to get email as mentioned here https://learn.microsoft.com/en-us/graph/api/message-get?view=graph-rest-1.0&tabs=http
Is there a way where I can listen to new incoming mail instead of calling the GET api to fetch new mail every time?
You can follow the doc to use the Microsoft Graph API to get change notifications
POST https://graph.microsoft.com/v1.0/subscriptions
Content-Type: application/json
{
"changeType": "created,updated",
"notificationUrl": "https://webhook.azurewebsites.net/api/resourceNotifications",
"resource": "/teams/{id}/channels/{id}/messages",
"includeResourceData": true,
"encryptionCertificate": "{base64encodedCertificate}",
"encryptionCertificateId": "{customId}",
"expirationDateTime": "2019-09-19T11:00:00.0000000Z",
"clientState": "{secretClientState}"
}
Resources available for email are :
Changes to all messages in a user's mailbox:-
/users/{id}/messages
Changes to messages in a user's Inbox:-
/users/{id}/mailFolders('inbox')/messages
Note: you will only get the notification for new emails but not the resource data in v1.0 endpoint , where as you can get the resource data by adding the property "includeResourceData": true.
For more info , see the doc - https://learn.microsoft.com/en-us/graph/webhooks-with-resource-data?context=graph%2Fapi%2F1.0&view=graph-rest-1.0
Hope this helps
Thanks
I'm writing a Google Hangouts Chat bot with Google Apps Script. The bot authenticates with a third party service with the apps script OAuth2 library. As documented in this How-To, when a message is received by the bot but authentication with the third party service is required, the bot sends a special REQUEST_CONFIG reply to Chat containing the configCompleteRedirectUrl.
var scriptProperties = PropertiesService.getScriptProperties();
function onMessage(event) {
var service = getThirdPartyService();
if (!service.hasAccess()) {
return requestThirdPartyAuth(service, event);
}
Logger.log('execution passed authentication');
return { text: 'Original message ' + event.message.argumentText };
}
function getThirdPartyService() {
var clientId = scriptProperties.getProperty('CLIENT_ID');
var clientSecret = scriptProperties.getProperty('CLIENT_SECRET');
return OAuth2.createService('ThirdPartyApp')
// Set the endpoint URLs.
.setAuthorizationBaseUrl('https://...')
.setTokenUrl('https://.../oauth/token')
// Set the client ID and secret.
.setClientId(clientId)
.setClientSecret(clientSecret)
// Set the name of the callback function that should be invoked to
// complete the OAuth flow.
.setCallbackFunction('authThirdPartyCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
.setCache(CacheService.getUserCache())
.setLock(LockService.getUserLock())
// Set the scope and other parameters.
.setScope('...')
.setParam('audience', '...')
.setParam('prompt', 'consent');
}
function requestThirdPartyAuth(service, event) {
Logger.log('Authorization requested');
return { "actionResponse": {
"type": "REQUEST_CONFIG",
"url": service.getAuthorizationUrl({
configCompleteRedirectUrl: event.configCompleteRedirectUrl
})
}};
/**
* Handles the OAuth callback.
*/
function authThirdPartyCallback(request) {
var service = getThirdPartyService();
var authorized = service.handleCallback(request);
if (authorized) {
Logger.log("user authorized");
//https://stackoverflow.com/a/48030297/9660
return HtmlService.createHtmlOutput("<script>window.top.location.href='" + request.parameter.configCompleteRedirectUrl + "';</script>");
} else {
Logger.log("user denied access");
return HtmlService.createHtmlOutput('Denied');
}
}
The service defines a callback authentication function, which in turn sends the browser to the configCompleteRedirectUrl. After this URL has been reached, the original message is supposed to be sent or re-dispatched a second time (see How-To step 7.3).
The authentication callback is successful because the last page displayed in the browser OAuth flow is the one specified in event.configCompleteRedirectUrl. Within the Chat window, the configuration prompt is erased, and the original message is changed to public. However, the original message is not dispatched again. The last log displayed in the apps script console is from the authentication callback event.
Is there something I have done incorrectly that prevents the original message from being dispatched again?
After much back and forth with a Google support team member, it turns out that there is a bug in the Hangouts Chat implementation when run against the V8 Apps Script runtime.
My appsscript.json file had "runtimeVersion": "V8" set. The re-dispatch does not work in this scenario. After I reverted to "runtimeVersion": "STABLE" in appsscript.json and re-deployed my scripts, the re-dispatch started working.
I am trying to add an app to our SharePoint Online site using the template from https://learn.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part and we get the error below when we deploy to SharePoint and add the app/Web part to a test SharePoint site. We are using TypeScript as the template uses.
Has anyone else encountered this issue or know where to look for the issue?
Found [object Object]Driver Display External Error: Error: AADSTS500011: The resource principal named https://driverdisplayexternal.azurewebsites.net was not found in the tenant named 7018324c-9efd-4880-809d-b2e6bb1606b6. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant. Trace ID: 358b22eb-cd2c-4091-b592-5a57cbc21d00 Correlation ID: ec96d656-1a36-42e2-a2b9-3ff78efc1e2e Timestamp: 2019-10-01 16:26:06Z
We have added a call to our own client as shown below. We are not sure why the resource principal was not found. The Tenant ID's match and things seem to be set up properly for authentication.
HelloWorldWebPart.ts
...
this.context.aadHttpClientFactory
.getClient('https://driverdisplayexternal.azurewebsites.net')
.then((client: AadHttpClient): void => {
client
.get('https://driverdisplayexternal.azurewebsites.net/api/values', AadHttpClient.configurations.v1)
.then((response: HttpClientResponse): Promise < Order[] > => {
this.domElement.innerHTML += 'Received a response from Driver Display External: ' + response;
return response.json();
})
.catch(error => {
this.domElement.innerHTML += 'Driver Display External Error: ' + error;
console.error(error);
});
});
...
package-solution.json
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "helloworld-webpart-client-side-solution",
"id": "**ID**",
"version": "4.1.0.0",
"includeClientSideAssets": true,
"isDomainIsolated": false,
"webApiPermissionRequests": [
{
"resource": "DriverDisplayExternal",
"scope": "User.Read.All"
}
]
},
"paths": {
"zippedPackage": "solution/helloworld-webpart.sppkg"
}
}
Any help or direction to where the issue may be would be very appreciated. Thanks in advance!
Never used this API, but if I had to guess you need to change the value here:
.getClient('https://driverdisplayexternal.azurewebsites.net')
You can use either the client id / application id, or the application ID URI.
Sometimes this problem can occurr when you set a wrong name for the scope you are requesting access for or another configuration parameter.
I suggest to check carefully the scopes name, or maybe directly use the "copy" button from the Azure portal.
In my case it was a simple typo on a scope name.
Not sure if you figured the answer or not. When you used SPFx to request your own custom web api end point. there are couple steps:
request the permission so that you can go to SPO admin to approve the permission you request. for this case, the webApiPermissionRequests->resources needs to your AAD Application's Service Principal DisplayName. once you had AAD App create, you can run Get-AzureADServicePrincipal to get all your ServicePrincipal.
once you request the permission, from your code, you need to call AadHttpClient.getClient() to get aadHttpClient object based on the api resourceEndpoint you want, for this case, you need to pass your web api's Application ID URI which can be found from your AAD App's manifest->"identifierUris". General speaking, this should be something like api://[clientid] format. but you can change it to any unique value.
I hope it helps.
In my case i had to use the App Id when i was consuming a multi tenant API.
In my case, TenantId and ClientId were both ok.
They can be found in AAD. TenantId is right there on landing page:
and then on the same page click Applications then tab All Applications find your application there should be ClientId check if they match.
If that is still not enough, click on the application and find roles
For me, it was roles that were missing after adding those wheels started rolling again:
I execute this code to push notifications to mobile device using FCM library
public string PushFCMNotification(string deviceId, string message)
{
string SERVER_API_KEY = "xxxxxxxxxxxxxxxxxxxxxxx";
var SENDER_ID = "xxxxxxxxx";
var value = message;
WebRequest tRequest;
tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
var data = new
{
to = deviceId,
notification = new
{
body = "This is the message",
title = "This is the title",
icon = "myicon"
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
now, how to send message to multi device,
assume that string deviceId parameter replaced with List devicesIDs.
can you help
Update: For v1, it seems that registration_ids is no longer supported. It is strongly suggested that topics be used instead. Only the parameters shown in the documentation are supported for v1.
Simply use the registration_ids parameter instead of to in your payload. Depending also on your use case, you may use either Topic Messaging or Device Group Messaging.
Topic Messaging
Firebase Cloud Messaging (FCM) topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. Based on the publish/subscribe model, topic messaging supports unlimited subscriptions for each app. You compose topic messages as needed, and Firebase handles message routing and delivering the message reliably to the right devices.
For example, users of a local weather forecasting app could opt in to a "severe weather alerts" topic and receive notifications of storms threatening specified areas. Users of a sports app could subscribe to automatic updates in live game scores for their favorite teams. Developers can choose any topic name that matches the regular expression: "/topics/[a-zA-Z0-9-_.~%]+".
Device Group Messaging
With device group messaging, app servers can send a single message to multiple instances of an app running on devices belonging to a group. Typically, "group" refers a set of different devices that belong to a single user. All devices in a group share a common notification key, which is the token that FCM uses to fan out messages to all devices in the group.
Device group messaging makes it possible for every app instance in a group to reflect the latest messaging state. In addition to sending messages downstream to a notification key, you can enable devices to send upstream messages to a device group. You can use device group messaging with either the XMPP or HTTP connection server. The limit on data payload is 2KB when sending to iOS devices, and 4KB for other platforms.
The maximum number of members allowed for a notification_key is 20.
For more details, you can check out the Sending to Multiple Devices in FCM docs.
You should create a Topic and let users subscribe to that topic.
That way, when you send an FCM message, every user subscribed gets it, except you actually want to keep record of their Id's for special purposes.
FirebaseMessaging.getInstance().subscribeToTopic("news");
See this link: https://firebase.google.com/docs/cloud-messaging/android/topic-messaging
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to": "/topics/news",
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!",
}
}
Please follow these steps.
public String addNotificationKey(
String senderId, String userEmail, String registrationId, String idToken)
throws IOException, JSONException {
URL url = new URL("https://android.googleapis.com/gcm/googlenotification");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
// HTTP request header
con.setRequestProperty("project_id", senderId);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
con.connect();
// HTTP request
JSONObject data = new JSONObject();
data.put("operation", "add");
data.put("notification_key_name", userEmail);
data.put("registration_ids", new JSONArray(Arrays.asList(registrationId)));
data.put("id_token", idToken);
OutputStream os = con.getOutputStream();
os.write(data.toString().getBytes("UTF-8"));
os.close();
// Read the response into a string
InputStream is = con.getInputStream();
String responseString = new Scanner(is, "UTF-8").useDelimiter("\\A").next();
is.close();
// Parse the JSON string and return the notification key
JSONObject response = new JSONObject(responseString);
return response.getString("notification_key");
}
I hope the above code will help you to send push on multiple devices.
For more detail please refer this link https://firebase.google.com/docs/cloud-messaging/android/device-group
***Note : Please must read the about creating/removing group by the above link.
A word of caution mentioned in FCM DOcument which is as follows,
Caution: Any apps that use device group messaging must continue to use the legacy API for the management of device groups (creating, updating, etc.). The HTTP v1 can send messages to device groups, but does not support management.
https://firebase.google.com/docs/cloud-messaging/migrate-v1
Also the Admin SDK's uses a Batch HttpPostrequest to make it easy for consumers, so if you want Device Group messaging you could still uses the New V1 FCM API, but using FCM Admin SDK.
Here is the code from Admin SDK which does this job for you.
Class Name: FirebaseMessagingClientImpl
for (Message message : messages) {
// Using a separate request factory without authorization is faster for large batches.
// A simple performance test showed a 400-500ms speed up for batches of 1000 messages.
HttpRequest request = childRequestFactory.buildPostRequest(
sendUrl,
new JsonHttpContent(jsonFactory, message.wrapForTransport(dryRun)));
request.setParser(jsonParser);
setCommonFcmHeaders(request.getHeaders());
batch.queue(
request, MessagingServiceResponse.class, MessagingServiceErrorResponse.class, callback);
}
Trying out the Content Service API and the example is returning HTML when it should be returning JSON, what am I doing wrong?
https://developers.google.com/apps-script/guides/content
function doGet(request) {
var events = CalendarApp.getEvents(
new Date(Number(request.parameters.start) * 1000),
new Date(Number(request.parameters.end) * 1000));
var result = {
available: events.length == 0
};
return ContentService.createTextOutput(JSON.stringify(result))
.setMimeType(ContentService.MimeType.JSON);
}
GAS from another file trying to make the request:
function myFunction() {
var url = "published URL";
url+="?start=1325437200&end=1325439000";
var options = {
method:"get"
}
var response = UrlFetchApp.fetch(url,options).getContentText();
response = JSON.parse(response); //error, unexpected token <
}
Your usage of ContentService is correct, the code works exactly as is. Here is a link to my copy of your code published as a web app:
https://script.google.com/macros/s/AKfycbzx2L643LHw0oQAq1jBmKQh2ju_znGfmdj78dUypj36iF-s91w/exec
The problem you are running into is related to Authorization or Authentication, if the published script is not authorized, an HTML error message is returned.
To check if that is your issue, simply access the published URL directly in your browser. If you see JSON displayed, then Authorization is not the problem. If you see the "Authorization is required to perform that action" error message, open your published script and choose "doGet" from the Run menu, then follow the authorization prompts.
More likely, the problem is related to how your script is published. In order to access your published script from another script, it must be published with the "Who has access to the app" setting as "Anyone, Even anonymous". If you use any other value, Google returns an HTML login page instead of your JSON response, and you get the error you are seeing.
This happens because requests sent from Google Apps Script via URLFetchApp are not authenticated, they don't carry the credentials of the user running the code with them, and come in as anonymous requests.
If you don't allow "Anyone, even anonymous" in your publishing settings, Google redirects non-authenticated requests to the Google login page.