mulesoft google connector to create an event - google-calendar-api

I'm getting below error when trying to create a google event from anypoint studio using google connector.
OAuth authorization dance not yet performed for resourceOwnerId null
Basically to test this functionality, I did below
I took a listener connector (path:/hello) and configured with local host 8081
Dragged google calendar event insert connector and configured with below details
Base url: https://www.googleapis.com/calendar/v3
consumer secret : Entered corporate clent id
Consumer secret:Entered secret key
Authorization url : https://accounts.google.com/o/oauth2/auth
Access token url : https://accounts.google.com/o/oauth2/token
Scopes: https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.events.readonly https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/calendar.settings.readonly
Call back path : /oauth2callback
Authorize path : /authorize
external callback url : http://localhost:8081/oauth2callback
I left remaining below fields empty in the google calendar connecter.
Resource Owner id
Before
after
Object store
In between, HTTP Listener and Google calendar events Insert connecter, I placed Transform message and written below Dataweave
%dw 2.0
output application/json
---
{
summary: payload.summary,
start: {
dateTime: payload.start.dateTime,
timeZone: payload.start.timeZone
},
end: {
dateTime: payload.end.dateTime,
timeZone: payload.end.timeZone
}
}
Below is the JSON input I'm giving from the postman, url being http://localhost:8081/hello
{
"end": {
"datetime": "2022-05-19T16:00:00+05:30",
"timezone":Asia/Chennai
},
"start": {
"datetime": "2022-05-19T14:00:00+05:30",
"timezone":Asia/Chennai
},
"summary":"First PO from Mulesoft Google connector",
"description":"First desc from Mulesoft Google connector",
"location":"Hyderabad",
"attendees":[
{
"email":"testmail#email.com"
}
]
}
I'm using anypoint studio 7.8.0.
Thanks in advance.

You need to start the OAuth dance first, to get the access token.
You can start it by hitting the Authorize path that you have configured in your app, which in your case is http://localhost:8081/authorize
After that you will be redirected to Google sign in page. If the Google oauth credentials are configured correctly the mule app will get the access token and use it for the future requests.

Related

Need to redirect from Web appplication to Zoho Desk

I have Zoho desk trail account.
We want to redirect from our web application to Zoho Desk Add Ticket page by clicking button.
I have configure SAML SSO from below mention link:
https://help.zoho.com/portal/en/kb/desk/for-administrators/user-access-and-security/articles/setting-up-saml-single-signon-for-help-center
How can i achieve this without login or auto signup/signin into Zoho Desk using SAML SSO?
Web application in .net core.
If any one have done this using code then please reply.
I have found one solution for this.
Download "Component SAML" package which is paid package, but you will get 30 day trial version or Install NuGet package "ComponentSpace.saml2".
Creates a self-signed X.509 certificate.
Upload public key on Zoho Desk SAML Configuration and add private key in your project (under certificate folder).
For Dot net core application you need to add below settings in appsettings.json file.
"SAML": {
"$schema": "https://www.componentspace.com/schemas/saml-config-schema-v1.0.json",
"Configurations": [
{
"LocalIdentityProviderConfiguration": {
"LocalCertificates": [
{
"FileName": "certificates/idp.pfx",
"Password": "password"
}
]
},
"PartnerServiceProviderConfigurations": [
{
"Name": "{Entity Id from Zoho desk SAML Screen}",
"SignSamlResponse": true,
"AssertionConsumerServiceUrl": {Help Center SAML Response URL}
}
]
}
]
},
"ZohoDeskSettings": {
"PartnerName": "{Entity Id from Zoho desk SAML Screen}",
"RelayState": "{url on which you want to redirect after SSO}"
}
Add below code in Startup.cs (ConfigurationService method)
services.AddSaml(Configuration.GetSection("SAML"));
Add below code in your controller from where you will click link to redirect to zoho portal
[Authorize]
[HttpGet]
public async Task<IActionResult> InitiateSingleSignOn()
{
// Get the name of the logged in user.
var userName = User.Identity.Name;
// For demonstration purposes, include some claims.
var attributes = new List<SamlAttribute>()
{
new SamlAttribute(ClaimTypes.Email, /*{Users Email}*/),
new SamlAttribute(ClaimTypes.GivenName, /*{Users FirstName}*/),
new SamlAttribute(ClaimTypes.Surname, /*{Users LastName}*/),
};
var partnerName = /*{Get setting from appsettings.json}*/;
var relayState = /*{Get setting from appsettings.json}*/;
// Initiate single sign-on to the service provider (IdP-initiated SSO)
// by sending a SAML response containing a SAML assertion to the SP.
// The optional relay state normally specifies the target URL once SSO completes.
await _samlIdentityProvider.InitiateSsoAsync(partnerName, userName, attributes, relayState);
return new EmptyResult();
}
You can also check example provided by Component SAML

Firebase Realtime Database returns 401 when trying to authenticate?

I am using REST API in my app to communicate with a Firebase RTDB, and trying to use a Google Access Token to authenticate my requests.
My issue is that with even the most permissive Rules on the database, I get HTTP error 401 in response to queries that try to authenticate.
For example, say I try to put some data in my database with the following command, I get 401 in return (all the values within < > are placeholders):
curl -XPUT -d '{ "UserID" : "<GOOGLE_UID>", "UserName" : "Clicksurfer", "CompletionMoves" : 8, "CompletionTime" : 16.21979 }' https://<FIREBASE_URL>.firebaseio.com/Level2/<GOOGLE_UID>.json/?access_token=<GOOGLE_ACCESS_TOKEN>
401
The strangest part is, when I abandon the use of access token altogether the query works:
curl -XPUT -d '{ "UserID" : "<GOOGLE_UID>", "UserName" : "Clicksurfer", "CompletionMoves" : 8, "CompletionTime" : 16.21979 }' https://<FIREBASE_URL>.firebaseio.com/Level2/<GOOGLE_UID>.json
200
As I said, I am currently using the most permissive rules for debugging:
{
"rules": {
".read": true,
".write": true
}
}
Any idea what might be causing this? Thanks in advance
EDIT:
I use the Google Play Games plugin for Unity in my project, among other things to get the AuthCode.
In order to do this, I needed to do a couple of things:
When building the config for Google Play Games during startup, I made sure to call the RequestServerAuthCode(false) method
Have the user login after Google Play Games sets up
Make sure that the relevant ClientID was supplied to Unity (in this case, it is a web client that has auth permissions on my Firebase rtdb).
This all looks like this:
public class GPGSAuthentication : MonoBehaviour
{
public static PlayGamesPlatform platform;
void Start()
{
if (platform == null)
{
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().RequestServerAuthCode(false).Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.DebugLogEnabled = true;
platform = PlayGamesPlatform.Activate();
}
Social.Active.localUser.Authenticate(success =>
{
if (success)
{
Debug.Log("GSPS - Logged in successfully");
}
else
{
Debug.Log("GSPS - Falied to login");
}
});
}
}
Now that we've done this, we can call PlayGamesPlatform.Instance.GetServerAuthCode() in order to get the AuthCode.
I traded in my AuthCode for an Access Token by sending a POST request to https://www.googleapis.com/oauth2/v4/token. In my query, I supply 4 fields:
client_id, which has the ID of the previously used client (where we got the AuthCode from).
client_secret, which has the correlating secret.
grant_type, which is always with the value "authorization_code"
code, which has the value of the AuthCode we got.
In response, I get a 200 response with 4 parameters:
access_token, the token I (fail to) use when authenticating against my Firebase rtdb.
token_type, the type of the aforementioned token.
expires_in, the amount of time before the token expires (I presume in seconds unit)
refresh_token, a token which can be used in order to get a new access_token without having to keep the Google user connected.
I then supply this access_token value to the queries I send to my DB, and promptly get the 401 error.

Can I import OneSignal tokens to FCM?

I have several thousand OneSignal web push notification tokens I want to import to FCM. Is there a way to do this?
I see this endpoint which requires the https://fcm.googleapis.com/fcm/send/...key... endpoint that OneSignal gives me, but I don't know what to put in for auth and p256dh.
https://developers.google.com/instance-id/reference/server#create_registration_tokens_for_apns_tokens
So yes this can be done. First you will need to contact OneSignal support and get the public and private VAPID keys for your app. Each app in your dashboard will have a different set.
Next you will need to make an API call to OneSignal in order to export the users in a CSV file.
You can find the API url in the docs and use curl or use your favorite language. I used Node + Axios to make my calls. The API call will supply you with a link to download the CSV.
Here is the documentation https://documentation.onesignal.com/reference#csv-export
You want to make sure you add the "extra_fields" parameter to your request with the "web_auth" and "web_p256" fields added. The CSV will provide you with the other piece of the puzzle which is the endpoint url in their identifier column.
Once you have all this information you can now send pushes using a library such as web-push for Node
https://github.com/web-push-libs/web-push
Hope that helps!
EDIT
As Cedric stated the actual push payload is a little bit more complicated because you need to comply with the OneSignal Service worker data handling.
You can see the formatting starting at line 313 here
If you are using a library like web-push for Node to send your push payloads your payload would be formatted something like this for a standard push to a OneSignal service worker.
const uuidv1 = require('uuid/v1')
const webpush = require('web-push')
let subscription = {
endpoint: 'USER ENDPOINT URL',
keys: {
auth: 'USER AUTH KEY',
p256dh: 'USER P256 KEY'
}
}
let vapid = { private: 'VAPID PRIVATE KEY', public: 'VAPID PUBLIC KEY' }
// Format Message for OneSignal Service Worker
let notification = JSON.stringify({
custom: {
i: uuidv1(), //Generate UUID for the OneSignal Service worker to consume
u: 'CLICK URL'
},
title: 'TOP TITLE',
alert: 'MESSAGE BODY',
icon: 'ICON IMAGE URL'
})
webpush.setVapidDetails('mailto: sendError#YourEmail.com', vapid.public, vapid.private)
webpush.sendNotification(subscription, notification)
It's much more complex than Dan's answer. If your users don't subscribe to your own service worker, it won't work. OS will send its default notification when an 'unknown' error occurs, which it will send "You have new updates" as a notification to the user even though you passed different payload. You also need to pass: "custom": { "i": uuidv1() } to your payload for it to work. (don't forget to install uuid first through npm and call it). Check out this link and you'll figure out what other payload props you need to pass.

LinkedIn API V1 - Receiving “Unauthorized request” when posting to Companies/{companyId}/shares

We are receiving 403 responses when posting to the company shares endpoint.
This happens when using the example company 2414183 and our chosen company.
The call to is-company-share-enabled endpoint is successful.
We are checking that the user is authenticated before making the request.
The LinkedIn profile we are using is set up as an company admin.
The domains we are calling from have been added to the Valid SDK Domains list.
It looks like the app usage & limits is counting these failed requests.
We can successfully post from Postman to both companies shares with varying payloads (using Postmans in built OAuth 2.0).
Would anyone be able to help us with this?
Here are some of the failed request ids
58LETKI9LD
RBG4DRL5VT
XYCOX9XID1
JPY6AORIKW
The code being used is mostly from the developer guides.
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: [removed]
authorize: false
</script>
$scope.postToLinkedInCompanyPage = function () {
if (!IN.User.isAuthorized()) {
IN.User.authorize(shareLinkedInCompanyPageContent);
}
else {
shareLinkedInCompanyPageContent();
}
};
function shareLinkedInCompanyPageContent() {
if (!IN.User.isAuthorized()) {
console.error("User not authorized");
return;
}
var payload = {
"comment": "Check out developer.linkedin.com! http://linkd.in/1FC2PyG",
"visibility": {
"code": "anyone"
}
};
var cpnyID = [removed];
IN.API.Raw("/companies/" + cpnyID + "/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
}
function onSuccess(data) {
console.log(data);
}
function onError(error) {
console.log(error);
}
06/12/2018 - Update
I tried the code out into a simple web app.
Converting the angular into plain JavaScript.
When posting to the test company 2414183, I still receive 403
POST https://api.linkedin.com/v1/companies/2414183/shares?format=json 403
{errorCode: 0, message: "Unauthorized request", requestId: "259UFIKLIR", status: 403, timestamp: 1544085898666}
Version 1 of the API is no longer supported.
Here is an extract from the LinkedIn dev blog
Update: As of May 1, 2019, Version 1.0 of our API is no longer
supported. Applications requesting Version 1.0 APIs may experience
issues as we begin to remove services. To find the latest updates, go
to the new LinkedIn Developers site at
https://www.linkedin.com/developers/. You can learn more about our
Version 2.0 APIs, our developer program, and how to migrate your apps.
I'll update the tags and header so this isn't picked up in future searches

Service Worker - Push notification with VAPID prv/pub keys

A couple of years ago I implemented push notification with service worker on a project I was working on, by registering an app on Firebase, and using the registration number as part of the manifest.json file on the server side app. In that case I requested the user to allow notifications, got the browser registration once, saved on server side, and all works fine.
I'm now trying to implement a similar solution, but using the VAPID (https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications#using_vapid).
Browser registers correctly, sends the registration to the server side app, and the app is able to send push notifications.
The issue I got is that after at least 24 hours, when I try to send a push notification to an already registered subscription, I get InvalidSubscription response (410 NotRegistered).
Using VAPID, does the browser registration expire after a few hours? do I need to get new registration every certain amount of hours? If yes, how? For example, if user never revisits the site within a day or so, how am I able to keep sending them notifications? I can't find any clear reference for this issue I'm experiencing.
Here is the JS code I use within the SW to get the browser registration:
function postPushReg(sub){
var rawKey = sub.getKey ? sub.getKey('p256dh') : '';
var key = rawKey ?
btoa(String.fromCharCode.apply(null, new Uint8Array(rawKey))) :
'';
var rawAuthSecret = sub.getKey ? sub.getKey('auth') : '';
var authSecret = rawAuthSecret ?
btoa(String.fromCharCode.apply(null, new Uint8Array(rawAuthSecret))) :
'';
fetch('https://XXXXX', {
method: 'post',
headers: {'Content-type': 'application/json'},
body: JSON.stringify({endpoint: sub.endpoint, key: key, authSecret: authSecret}),
});
}
self.addEventListener('install', function(event){
self.registration.pushManager.getSubscription()
.then(function(sub){
if (sub) return postPushReg(sub);
return self.registration.pushManager.subscribe({userVisibleOnly: true,
applicationServerKey: urlB64ToUint8Array('XXX')})
.then(function(sub){
postPushReg(sub);
});
});
});
self.addEventListener('push', function(e){
...
});
This is the Rails/Ruby server side gem (webpush) I use to send the notification:
Webpush.payload_send(
message: "msg",
endpoint: j['endpoint'],
p256dh: j['key'],
auth: j['authSecret'],
vapid: {
subject: "mailto:XXXX",
public_key: "XXX",
private_key: "XXX",
}
)
Again, within the first few hours everything works, then I get 410 NotRegistered response.
Trying the same suggestion posted here: Web Push with VAPID: 400/401 Unauthorized Registration , it is now working fine. I get the browser registration only once, and after 2 days it is still working fine

Resources