I would like to fetch a user's email using the C# Facebook SDK. How can I do so? I've tried the code below, but I just get an empty email. Is it because I somehow need to ask for more rights? If so, how do I do that?
Facebook.FacebookClient fbc = new Facebook.FacebookClient(user.MobileServiceAuthenticationToken);
dynamic clientCredentials = await fbc.GetTaskAsync("oauth/access_token",
new{client_id = facebookClientId,client_secret = facebookClientSecret,
grant_type = "client_credentials",redirect_uri = "https://xxx.azure-mobile.net/signin-facebook"});
fbc.AccessToken = clientCredentials.access_token;
fbc.AppId = facebookClientId;
fbc.AppSecret = facebookClientSecret;
string id = user.UserId.Replace("Facebook:", string.Empty);
dynamic result = await fbc.GetTaskAsync(id + "?fields=id,name,picture,last_name,first_name,gender");
Best regards
TJ78
You need to gather the email permission in the login Url's scope parameter, otherwise you will not be able to receive the email field.
Related
I have a Grails project (v2.4.2) that is making use of the spring-security-facebook:0.17 plugin to authenticate via Spring Security. At first sight, all seems well. However, there is a large set of users that for some unknown reason I cannot access their email address. I am using spring social to grab the email. I have permission and it is set in the scope. Here is a code snippet where I authenticate a new user:
log.info("Create domain for facebook user $token.uid")
//Use Spring Social Facebook to load details for current user from Facebook API
log.info("create: FacebookAuthToken: $token")
log.info("created FacebookAuthToken.FacebookAccessToken = ${token.accessToken}")
Facebook facebook = new FacebookTemplate(token.accessToken.accessToken)
org.springframework.social.facebook.api.User fbProfile = facebook.userOperations().getUserProfile()
// Check if email is actual granted because in production some are coming back null
boolean isEmailGranted=false
List<Permission> permissions = facebook?.userOperations()?.getUserPermissions()
String permissionString = "["
for (int i=0;i<permissions.size();i++) {
permissionString += "["+ permissions[i].getName() + ":" + permissions[i].getStatus()+"]"
if (permissions[i].getName()=="email" && permissions[i].isGranted())
isEmailGranted=true
}
permissionString += "]"
log.info("create: Facebook Permissions = " + permissionString)
def grailsWebRequest = WebUtils.retrieveGrailsWebRequest()
def flash = grailsWebRequest.flashScope
if (!isEmailGranted) {
log.warn("create: Unable to subscribe facebook user because email priviledge was not granted.")
flash.message = 'Login to Facebook failed. We must have access to your email address in order to proceed with login.'
throw new InsufficientAuthenticationException("Facebook email not accessible")
}
log.info("created: ")
String email = fbProfile.getEmail()
String firstName = fbProfile.getFirstName()
String lastName = fbProfile.getLastName()
String fullName = fbProfile.getName()
String username = firstName
String password = token.accessToken.accessToken
if (!email) {
log.error("create: Permission was granted to use facebook email but the value is null.")
flash.message = 'Login to Facebook failed. We are temporarily unable to access your email although permission has been granted'
throw new InsufficientAuthenticationException("Facebook email not accessible for unknown reason")
}
Why would I receive an empty email when permission has been granted? Is there a preferred method for handling this behavior (other than failing the authentication and making up a fake email address). Many thanks!
The documentation for the 'email' field of the 'user' object ( https://developers.facebook.com/docs/reference/api/user/ ) clarifies the expected behaviour here, which is:
"this field will not be returned if no valid email address is available"
There is a detailed explanation about different situations where an email won't be sent. Please check it out:
https://developers.facebook.com/bugs/298946933534016/
I hope it helps.
I'm building an App with ASP.NET MVC 5 and Identity.
So far the login is working correctly.
Here the auth:
var fb = new FacebookAuthenticationOptions();
fb.Scope.Add("email");
fb.Scope.Add("friends_about_me");
fb.Scope.Add("friends_photos");
fb.AppId = "";
fb.AppSecret = "";
fb.Provider = new FacebookAuthenticationProvider() {
OnAuthenticated = async FbContext => {
FbContext.Identity.AddClaim(
new System.Security.Claims.Claim("FacebookAccessToken", FbContext.AccessToken));
}
};
fb.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
app.UseFacebookAuthentication(fb);
I'm trying to get the friends list. I've been looking for a few examples but none is working with this version of MVC 5.
My question is. How can I fetch all the friends with this version?
I don't want to use Javascript API, I want all the code in c# and then send to the view.
I think I just need to rewrite the login and store the access token in the session, and then simply call var client = new FacebookClient(TOKEN);
So how can I rewrite the login?
You've already got everything you need. The OnAuthenticated callback you've set adds a claim containing the access token for Facebook. You just need to pull the claim for the user:
var identity = (ClaimsIdentity)User.Identity;
var facebookClaim = identity.Claims.FirstOrDefault(c => c.Type == "FacebookAccessToken");
if (facebookClaim != null)
{
// access facebook API with `facebookClaim.Value`
}
And if it exists, then you can use the Facebook API to pull in their friends by making standard HTTP calls via something like HttpClient.
I am using https://github.com/sanjeevdwivedi/facebook-csharp-sdk to integrate facebook in my wp8 app.
I want to know how to access the user email id using facebook-csharp-sdk below is the code I am using
FacebookSession session = FacebookSessionClient.LoginAsync("user_about_me,read_stream");
FacebookClient _fb = new FacebookClient(session.AccessToken);
dynamic parameters = new ExpandoObject();
parameters.access_token = session.AccessToken;
parameters.fields = "email,first_name,last_name";
dynamic result = await _fb.GetTaskAsync("me", parameters);
But I am getting only firstname , lastname and id of the logged in result field. Please suggest where am i missing?
You should ask for the email permission.
FacebookSession session = FacebookSessionClient.LoginAsync("user_about_me,read_stream,email");
The last item in the LoginAsync params I placed is email
See permissions for more info
So I tried to post on my friends wall using the following code:
var fb = new FacebookClient(_accessToken);
dynamic parameters = new ExpandoObject();
parameters.message = "Google is your friend";
parameters.link = "http://gidf.de/";
parameters.Name = "Test";
parameters.from = new { id = "100000", name = "me" };
parameters.to = new { id = "1000001", name = "friend" };
dynamic result = fb.Post("1000001/feed", parameters);
However, I get told that my application does not support this. I did some googling work, and read that [USER_ID]/feed is deprecated and that I have to invoke the feed dialog to ask the user to publish it. How would I go on doing this with the C# SDK?
As of February 6, 2013, you can't post to Friends Timeline on behalf of the user.
Read Here: https://developers.facebook.com/roadmap/completed-changes/
Client-Side you can use the FB.ui method to pop up the feed dialog.
Here's an example: https://stackoverflow.com/a/15426243/1405120
Server-Side, you can use the URL Redirection.
https://www.facebook.com/dialog/feed?
app_id=458358780877780
&link=https://developers.facebook.com/docs/reference/dialogs/
&redirect_uri=https://mighty-lowlands-6381.herokuapp.com/
Read more about Feed dialog here, https://developers.facebook.com/docs/reference/dialogs/feed/
I am designing an app for iPhone and android in which I have to integrate facebook, twitter, yahoo, gmail, openId. I had integrated facebook and twitter, but how to go for yahoo, gmail and openId? How to login these through app and get the user information?
Please do show me a way to implement this. Any tutorial may help.
Thanks.
To integrate gmail may this url's help you
Google's documentation
Introduction about integrating gmail with iphone
Examples to integrate with iphone
Api's for integrating blogger,google analytics etc
For yahoo you can use this
String YAHOO_RESOURCE_URL = "http://social.yahooapis.com/v1/me/guid/profile?fomat=xml";
String CALLBACK_URL = "oauth://testApp";
String YAHOO_REQUEST_TOKEN_URL = "https://api.login.yahoo.com/oauth/v2/get_request_token";
String YAHOO_ACCESS_TOKEN_URL = "https://api.login.yahoo.com/oauth/v2/get_token";
String YAHOO_AUTHORIZE_URL = "https://api.login.yahoo.com/oauth/v2/request_auth";
// Oauth consumer and provider.
CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(Constants.YAHOO_CONSUMER_KEY, Constants.YAHOO_CONSUMER_SERECT_KEY);
OAuthProvider provider = new CommonsHttpOAuthProvider(YAHOO_REQUEST_TOKEN_URL , YAHOO_ACCESS_TOKEN_URL, YAHOO_AUTHORIZE_URL);
provider.setOAuth10a(true);
// First retrive request token.
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
String yahooToken = consumer.getToken();
String yahooTokenSecret = consumer.getTokenSecret();
Open the authUrl in android web browser, this will launch login page, then after login will ask for permissions, accepting the permissions will return in your app using callback url.
Now,
In onResume
Uri uri = this.getIntent().getData();
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
String oauthToken = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_TOKEN);
String oauthVerifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
consumer = new CommonsHttpOAuthConsumer(Constants.YAHOO_CONSUMER_KEY, Constants.YAHOO_CONSUMER_SERECT_KEY);
consumer.setTokenWithSecret(yahooToken, yahooTokenSecret);
provider = new CommonsHttpOAuthProvider(YAHOO_REQUEST_TOKEN_URL, YAHOO_ACCESS_TOKEN_URL, YAHOO_AUTHORIZE_URL);
provider.setOAuth10a(true);
// Now retrive access token
provider.retrieveAccessToken(consumer, oauthVerifier);
String token = consumer.getToken();
String tokenSecret = consumer.getTokenSecret();
consumer.setTokenWithSecret(token, tokenSecret);
// Get the GUID from this.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet("http://social.yahooapis.com/v1/me/guid?format=json");
consumer.sign(request);
HttpResponse response = httpClient.execute(request);
Parse the response to get GUID.
// Now use the GUID to get profile info.
DefaultHttpClient httpClient = new DefaultHttpClient();
String strUrl = "http://social.yahooapis.com/v1/user/"+ strGUID +"/profile?format=json";
HttpGet request = new HttpGet(strUrl);
consumer.sign(request);
HttpResponse response = httpClient.execute(request);
Parse the response and njoy :)