Facebook Graph API "/userid/feed" returning Blank - c#

I'm using Facebook C# SDK and I can't seem to get feed data back using Graph API.
I've obtained the following extended permissions from the user:
scope=offline_access,publish_stream,publish_checkins,create_event,read_stream,user_about_me,user_events,user_hometown,user_location,user_photos,read_friendlists,read_requests,user_checkins,user_relationships,user_online_presence,user_notes,user_likes,user_work_history
I have an access token for offline access.
I'm able to retrieve userid/friends information without a hitch, but can't seem to get feed data.
I get the following returned:
{
"data": [
]
}
I obtained the token with type="client_cred" if that makes a difference. The process runs with user offline, so I'm not using the "me" alias.
Can someone give some direction on what I'm doing wrong?

A token obtained with type=client_cred means "the application on behalf of itself", rather than "the application on behalf of a specific user". This means that it can only see stuff that's visible to all users. If you want to grab information on behalf of a particular user, you need to use that user's access token that you acquired. Since you asked for offline_access, when you acquire an access token for a user, that token won't expire quickly, and you can keep it around in a database.

FB.init({
appId : 'YOUR APP ID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
Once you add this code. Facebook sets a cookie on you domain. The name of the cookie would be fbs_YourAppId .
You can read the cookie and get the access_token.
Alternately you can use a method provided by the Facebook Api Connect.js file to get the feed if the user is logged in.
FB.Api(). Please refer to http://developers.facebook.com/docs/reference/javascript/fb.api/ to know more about the method.
Happy coding :)

Related

How to properly use activateMembership to fully reactivate a closed user's membership?

How do we reactivate a closed user's membership through Admin API to make them fully active without triggering any emails from DocuSign?
The longer story.
I have been successfully using DocuSign API to create users with memberships, add their permission profiles and close their memberships. Our domain setup is configured for mandatory SSO and we are creating users with autoactivate flag set. Everything works fine so far, users are immediately active.
But the problems start when we want to anonymize the data of a user that has been closed for some time (for example, for GDPR reasons). It is impossible to fully update the user's data for closed membership because we get a partial update and a warning from DocuSign API: username_language_changes_ignored_warning, and indeed user's full name does not get changed.
So I thought of a workaround. I temporarily reactivate the membership of the closed user, then do the anonymization, and then close the membership again. But reactivation does not work.
I'm sending the following command to DocuSign Admin API:
var resp = await usersApi.ActivateMembershipAsync(options.OrganizationId, user.Id, membership.AccountId, new ForceActivateMembershipRequest
{
SiteId = user.SiteId
});
but DocuSign replies with
"error":"unauthorized","error_description":"Not Authorized"
It does not make much sense because we have user_write permission (otherwise we couldn't have created and closed the user in the first place). Actually, DocuSign API seems to often return unauthorized for cases when the actual problem is not authorization, which makes things confusing. Only when calling batch APIs, DocuSign usually returns more meaningful information.
One thing that I'm not sure of is membership.AccountId. We are using it as membershipId parameter because I could not find any other membershipId. Membership object from GetUserProfiles does not have any other id except AccountId, and GetUsers returns MembershipId=null. So it seemed reasonable to assume that membership id is the same as account id for that membership, especially since I have been successfully using account id also for CloseMemberships API request.
Another thing I found is that, when we attempt to reactivate the user through DocuSign Admin UI webpage, it asks to assign the permission profile. So, DocuSign seems to remove the permission profile we have set when creating the person and there is no way to assign the permission profile through ActivateMembership API. That might be the reason for "error":"unauthorized" - DocuSign does not know what permissions to restore for the reactivated user and so it throws the meaningless authorization error.
And one more thing - when reactivating the user manually through DocuSign Admin UI webpage, it suddenly has status Pending, although we have auto-activation for the domain set up and working when we create new users. This is a huge roadblock to the idea for the "reactivate - anonymize - close" workaround. We don't want users to receive any pending DocuSign activation emails when we have reactivated them for a second to be able to anonymize data and then close them again.
What is the solution to this? How do we reactivate users? Or how do we completely anonymize closed users without reactivation?
We appreciate your post, we'll address the different parts.
You should be able to update a user's details regardless of their status.
If you are getting a language error, make sure you input a valid language code,
you can find the list here:
https://developers.docusign.com/docs/admin-api/reference/usermanagement/esignusermanagement/updateuser/
To update a user's email you have to use "updateemailaddress" and it has to be an email with a claimed domain in DocuSign, to anonymize set it to anonym#yourcompany.com.
https://developers.docusign.com/docs/admin-api/reference/usermanagement/users/updateemailaddress/
To reactivate a user using the DocuSign Admin API you have to take two steps,
Here is the process:
How to reactivate a user in the Admin API
Generate an auth token with user_write and user_read permissions
Find the user/membership in question. In order to do so, you must make the GetUsers call with the account_id parameter and page through to find the user in question and capture the membership ID
https://developers.docusign.com/docs/admin-api/reference/users/users/getusers/
Example Call:
GET /organizations/[[Org_Id]]/users?account_id=[[AccountId]]&take=20&start=0
Response includes:
`{
"id": "9672a992-xxxx-xxxx-xxxx-8fb5c4b6d325",
"user_name": "Example User"
"first_name": "Example",
"last_name": "User",
"membership_status": "closed",
"email": "user#example.com",
"membership_created_on": "2021-01-1T10:10:10.10",
"membership_id": "b5283dfb-xxxx-xxxx-xxxx-eb0aeac16b8c"
}`
,
to page, look at the "paging" : { "next" } parameter to see the start / take values to use for the repeat call
At time of writing, getUsers with the Email Address parameter does NOT return the membership ID for the user's memberships
Furthermore, getUsers by email does not list closed memberships
use UpdateUser call to set user to Pending
Documentation: https://developers.docusign.com/docs/admin-api/reference/users/users/updateuser/
Example Call:
POST /organizations/[[Org_Id]]/users/profiles
{
"users": [
{
"id": "9672a992-xxxx-xxxx-xxxx-8fb5c4b6d325",
"site_id": 1,
"memberships": [
{
"account_id": "182e8dd4-xxxx-xxxx-xxxx-594834882eab",
"send_activation": true
}
]
}
]
}
Active user's membership using the membership ID
Documentation: https://developers.docusign.com/docs/admin-api/reference/users/users/activatemembership/
POST /organizations/[[org_id]]/users/[[user_id]]/memberships/[[membership_id]]
{
"site_id":"1"
}
We hope this helps.
Adrian
DocuSign Developer Support

Create user using Microsoft Graph

How do I create a user using Microsoft graph? For I am having issues with regards to permission failures during a save.
I do have few questions in mind.
Where will the user be created by calling create user API in graph ? Is it in Azure AD or somewhere else ?
I tried calling create user api by passing json and required headers, below is the error I get
Where exactly do I need to set the permission, I have already added permissions in the Application Registration Portal
But when API is executed it shows that I don't have enough permission.
FYI, I have registered the app using the same email id that I am using to test the APIs here https://developer.microsoft.com/en-us/graph/graph-explorer#
If I am not the admin, where exactly do I need to set or request for it ?
In order to create a User via Microsoft Graph, you need to request either Directory.ReadWrite.All or Directory.AccessAsUser.All permission.
Important: Directory.ReadWrite.All and Directory.AccessAsUser.All both require Admin Consent before you can use them. If you're using Graph Explorer then the URI you need to provide your tenant Admin will be generated for you. If you're doing this in your own application, you'll need to construct an Admin Consent URI yourself. You can find more details on this at v2 Endpoint & Admin Consent.
Once you have the proper permissions configured (and consented), you'll want to POST the following JSON body/payload to https://graph.microsoft.com/v1.0/users:
{
"accountEnabled": true,
"displayName": "displayName-value",
"mailNickname": "mailNickname-value",
"userPrincipalName": "upn-value#tenant-name.onmicrosoft.com",
"passwordProfile" : {
"forceChangePasswordNextSignIn": true,
"password": "password-value"
}
}
This will create a user with a temporary password. The user will be asked to set a new password as after as they authenticate for the first time.
Where will the user be created by calling create user API in graph ?
Is it in Azure AD or somewhere else ?
Yes, the user created is in the Azure AD.
I tried calling create user api by passing json and required headers,
below is the error I get
For your error, have you added the request body like the following, and this required admin:
Where exactly do I need to set the permission, I have already added
permissions in the Application Registration Portal
The required permissions to create application:
For the details, please read here.

How to get Page Access Token by code?

I need to generate a Page Access Token for a webpage that I have, this token will be used by the webpage to post to its Facebook Page feed.
This is what I do :
Go to Graph API Explorer
Choose my app from the dropdown
Click Get Access Token
Choose correct permissions(manage_pages/user_events)
To get the Page Access Token I have to run me/accounts in the Graph API Explorer. This will show all the pages I got with a new Page Access Token (short lived(about 60 min)) to each one.
This Page Access Token will work just fine to use in my C# code to post to the feed.
Problem
When another user uses my webpage to post a post I need to generate a new Page Access Token(in code) and then use it to post the userpost to the site´s facebook feed. The problem is that I could clearly not be there to grant the post so how do I handle this?
I could obviously not run the me/accounts(in code) command to get the Page Access Token from here.
I have looked at extended Access Token but this will last 60 days and then it will be the same problem as above.
What you need is an Extended Page Token:
generate User Access Token with manage_pages and publish_actions
generate Extended User Token (valid for 60 days): https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=[app-id]&client_secret=[app-secret]&fb_exchange_token=[short-lived-token]
call /me/accounts with the Extended User Token to get Extended Page Tokens
Extended Page Tokens are valid forever, so you don´t need to generate a new one all the time.
Source (including information about all the Tokens): http://www.devils-heaven.com/facebook-access-tokens/
On https://developers.facebook.com/docs/pages/access-tokens
Getting Page Access Tokens
GET /{page-id}?fields=access_token&access_token={user_access_token}
The response will look like this:
{
"access_token": "{your-page-access-token}",
"id": "{page-id}"
}

authorization: what is the flow for non-first time user?

I have a site (still on localhsot).
I want to authorize the user against Google and get permission to gmail scope.
I get a requestToken
Authorize it
Save requestToken from the queryString into a cookie (?)
(I don't have accessToken by now)
Upgrade it to accessToken
Then what?
I thought to save requestToken and accessToken in the DB with some user guid (?)
Are they both parmenent and uniqe?
Will it help next time to avoid the Upgrade it to accessToken
When the user come back for the second time - how will I retrieve its access token?
You will have to store the access token with the user data, yes. Then you will set the Forms Authorization cookie as normal against their username or id.
When they come back a second time, if they still have the cookie, then they will be signed in as normal.
If their cookie has expired, ask them to log in with their chosen provider (Google) and retrieve the token again. You will then have to search the data to see if any users have that token already, and if they do, log that user in as normal like you do the first time.
If they log in with a different provider, they will get a different token and will effectively be seen as a different user - how you handle this is a separate issue.

Service Account Google Analytics OAuth AccessType = Offline C#

I've got credentials of an account with access to Google Analytics,
I'm looking to utilise the Analytics Core Reporting API http://code.google.com/apis/analytics/docs/gdata/home.html
I've found examples which use username/password calling setUserCredentials, but have seen comments this is less secure/has a low request limit (And doesn't exist in the lastest client).
Plus I've seem examples which use oauth, but require user interaction and grant access to the users google account.
However I'm looking to run a service which doesn't require any user interaction, and connects to a predefined google account (un-related to the user viewing it).
I can then store the results in a database, and end users can query the results from the database.
I've seen information about using AccessType = Offline when you first login, which then returns an access token and a refreshtoken.
http://code.google.com/apis/accounts/docs/OAuth2WebServer.html#offline
In my example though, the end user will never login to the application.
Could I have a seperate admin application which gets a refresh token, and stores the refresh token in the config/lookup table?
Then the main application can use the refresh token pulling from the config/lookup table, and get an access token to be able to query the Google Analytics account.
I'm looking for a C# example which uses AccessType = Offline, and seperates out the fetching of the refresh token and using the refresh token to get an access token to query the google analytics account.
Create your app https://code.google.com/apis/console/
For you App, turn on access to Google Analytics, and create an OAuth 2.0 client ID for your website.
Browse to:
https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=YOUR_APP_ID.apps.googleusercontent.com&access_type=offline&scope=https://www.googleapis.com/auth/analytics.readonly&redirect_uri=HTTP://YOUR_CALL_BACK_URL
Having changed YOUR_APP_ID, YOUR_CALL_BACK_URL to the relevant values.
Important to include access_type=offline.
Press Grant Access, this will redirect to HTTP://YOUR_CALL_BACK_URL?code=THIS_IS_YOUR_CODE. Copy the code in the URL.
With the code, request the Refresh Token using CMD prompt.
curl -d "code=THIS_IS_YOUR_CODE&client_id=YOUR_APP_ID.apps.googleusercontent.com&client_secret=YOUR_APPS_SECRET_CODE&redirect_uri=HTTP://YOUR_CALL_BACK_URL&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token
Having changed THIS_IS_YOUR_CODE, YOUR_APP_ID, YOUR_APPS_SECRET_CODE, YOUR_CALL_BACK_URL to the relevant values.
Record the refresh_token returned.
Download the latest version of the Core Reporting V3.0 .net libraries
http://code.google.com/p/google-api-dotnet-client/wiki/Downloads
There is a bug in the current version of Google.Apis.Analytics.v3.cs, to fix this copy the code in this file to your local solution (And don’t reference Google.Apis.Analytics.v3.bin)
http://code.google.com/p/google-api-dotnet-client/source/browse/Services/Google.Apis.Analytics.v3.cs?repo=samples&name=20111123-1.1.4344-beta
And change the property Dimensions from a List<system.string> to a string.
Or you'll get an error like me and this guy did http://www.evolutiadesign.co.uk/blog/using-the-google-analytics-api-with-c-shar/
You can then use your Refresh Token, to generate you an Access Token without user interaction, and use the Access Token to run a report against Google Analytics.
using System;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using AnalyticsService = Google.Apis.Analytics.v3.AnalyticsService;
class Program
{
public static void Main()
{
var client = new WebServerClient(GoogleAuthenticationServer.Description, "YOUR_APP_ID.apps.googleusercontent.com", "YOUR_APPS_SECRET_CODE");
var auth = new OAuth2Authenticator<WebServerClient>(client, Authenticate);
var asv = new AnalyticsService(auth);
var request = asv.Report.Get("2012-02-20", "2012-01-01", "ga:visitors", "ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID");
request.Dimensions = "ga:pagePath";
request.Sort = "-ga:visitors";
request.MaxResults = 5;
var report = request.Fetch();
Console.ReadLine();
}
private static IAuthorizationState Authenticate(WebServerClient client)
{
IAuthorizationState state = new AuthorizationState(new string[]{}) { RefreshToken = "REFRESH_TOKEN" };
client.RefreshToken(state);
return state;
}
}
Great Answer Ian and it helped me to get going in the correct Direction more than any other answer I could find online. Something must have changed in the AnalyticsService object because the line:
var request = asv.Report.Get("2012-02-20", "2012-01-01", "ga:visitors", "ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID");
did not work for me and I had to use the following:
var request = asv.Data.Ga.Get("ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID", "2012-01-01", "2012-02-20", "ga:visitors");
Hopefully this will help others like your answer helped me. Thanks!
Ian's answer helped me a lot but I kept getting an error running the curl command. Did some research and found that the steps to get the access code and refresh token can be made easier by going to https://code.google.com/oauthplayground/ and checking your oAuth configuration settings. Top right of the page there is a settings button. selected "Use your own OAuth credentials". You can get your access code and request a refresh token all from here.
Hope this helps.
You can manually get a refresh token from the OAuth Playground.
If you are needing a refresh token for a Service Account as I was, make sure you
Click on the settings on the right.
Check Use your own OAuth credentials
Fill in your Client ID and Secret
Close the settings
Click the Refresh button on step 2
Then save the refresh token for use in your app

Categories