Error while getting Contacts from Microsoft graph api - swift

I am trying to fetch a user's Contacts using the Microsoft Graph SDK. I am able to get the user details using graphClient.me(), but when I try to get a list of contacts I am getting an error:
Graph SDK ERROR :
Error from data task :
Error Domain=com.microsoft.graph.errors
Code=400 "bad request"
UserInfo={
NSLocalizedDescription=bad request,
error= AuthenticationError : Error authenticating with resource
}
Graph SDK ERROR : Caused by request <NSMutableURLRequest: 0x1738bc70> {
URL: https://graph.microsoft.com/v1.0/me/contacts
}
My Code:
self.graphClient.me().contacts().request().getWithCompletion {
(_ contacts: MSCollection?,
_ nextRequest: MSGraphUserContactsCollectionRequest?,
_ error: Error?) in
if error == nil {
print("contacts \(contacts)")
}
else {
print("error \(error?.localizedDescription)")
}
}
My Scopes:
let SCOPES = ["openid", "profile","User.Read","Contacts.Read"]

The /contacts endpoint requires that the user has an accessible Exchange Mailbox. If the user doesn't have a mailbox provisioned in Exchange Online for this tenant, several endpoints that rely on Exchange will fail (/contacts, /events, /messages, etc.).

Related

Implementing Handover protocol for facebook chatbot throws error

My primary receiver is my dialogflow chatbot and my second one is the page inbox. I want to switch from the chatbot to the inbox by implementing:
request({
uri: 'https://graph.facebook.com/v3.2/me/pass_thread_control',
qs: {'access_token': 'pageAccessToken'},
method: 'POST',
json: {
recipient: {
id: 'userIdFromRequest'
},
target_app_id: 'pageInboxAppId'
},
}, (error: any, response: any, body: any) => {
console.log('BODY PASS THREAD CONTROL: ', body);
});
But I'm getting this error:
(#10) Only available to Primary and Secondary Receivers
When I try to get the secondary receivers:
request({
uri: 'https://graph.facebook.com/v3.2/me/secondary_receivers?fields=id,name&access_token=<page-access-token>',
qs: {'access_token': <page-access-token>},
method: 'GET',
}, (error: any, response: any, body: any) => {
console.log('BODY SECONDARY RECEIVERS: ', body);
});
I will get this error:
(#10) Only Main Receiver can call this API
But my chatbot IS the main receiver. I set in in page settings --> messenger platform.
I found out that this used to be a facebook bug, but it should have been fixed now.
Does someone has an idea what I'm doing wrong?
UPDATE
The app_roles parameter is missing in the web hook request. May it could have something to do with it?
Another mistake could be the userId. I took the senderId. The receiverId encounters an authorization error with errorCode 1 and the message "An unknown error occurred". I'm not sure which one is correct.<
UPDATE 2
The receiverId seems to be correct. The second request works with it. But still not the first: 500 internal server error...
Suddenly, it works now. Maybe they changed anything in the backend.

Silhouette and mobile application

I've used as example play-silhouette-angular-seed.
Authorization via Satellizer works fine.
When I try to authorize via iOs app I got next error:
com.mohiva.play.silhouette.impl.exceptions.UnexpectedResponseException:
[Silhouette][facebook] Cannot build OAuth2Info because of invalid response format:
List((/access_token,List(ValidationError(List(error.path.missing),WrappedArray()))))
I got an error 400 in this function from OAuth2Provider.scala :
protected def getAccessToken(code: String)(implicit request: RequestHeader): Future[OAuth2Info] = {
httpLayer.url(settings.accessTokenURL).withHeaders(headers: _*).post(Map(
ClientID -> Seq(settings.clientID),
ClientSecret -> Seq(settings.clientSecret),
GrantType -> Seq(AuthorizationCode),
Code -> Seq(code),
RedirectURI -> Seq(resolveCallbackURL(settings.redirectURL))) ++ settings.accessTokenParams.mapValues(Seq(_))).flatMap { response =>
logger.debug("[Silhouette][%s] Access token response: [%s]".format(id, response.body))
Future.from(buildInfo(response))
}
}
This error has been risen because Satellizer for authentication via Facebook send to server an 'authentication code' and Silhouette server use this code to get Facebook 'access token' and create user.
Facebook iOs SDK, instead, obtained 'Access token' and I've tried to send it to server in Json in field 'code' like 'Satellizer.
To resolve this issue I send an 'access token' in Json field named 'access_token' and use next code to authenticate mobile application:
class MobileSocialAuthController #Inject() (
val messagesApi: MessagesApi,
userService: UserService,
authInfoRepository: AuthInfoRepository,
socialProviderRegistry: SocialProviderRegistry,
val env: Environment[User, JWTAuthenticator])
extends Silhouette[User, JWTAuthenticator]
{
def authenticate(provider: String) = UserAwareAction.async(parse.json) {
implicit request =>
provider match {
case "facebook" =>
request.body.asOpt[OAuth2Info] match {
case Some(authInfo) =>
(socialProviderRegistry.get[FacebookProvider](provider) match {
case Some(p: FacebookProvider) =>
for {
profile <-p.retrieveProfile(authInfo)
user <- userService.save(profile)
authInfo <- authInfoRepository.save(profile.loginInfo, authInfo)
authenticator <- env.authenticatorService.create(profile.loginInfo)
token <- env.authenticatorService.init(authenticator)
} yield {
env.eventBus.publish(LoginEvent(user, request, request2Messages))
Ok(Json.obj("token" -> token))
}
case _ => Future.failed(new ProviderException(s"Cannot authenticate with unexpected social provider $provider"))
}).recover {
case e: ProviderException =>
logger.error("Unexpected provider error", e)
Unauthorized(Json.obj("message" -> Messages("could.not.authenticate")))
}
case _ =>
Future(BadRequest(Json.obj(
"message" -> "Bad OAuth2 json.")))
}
case _ =>
Future(BadRequest(Json.obj(
"message" -> "You can use only Facebook account for authentication.")))
}
}
}
As a result, I have a token which I use in ios application to obtain resources.
This happens when the OAuth2Provider gets a response it can't parse, which is, any non-success response. So there can be many reasons for this error, for instance the authorization code is invalid or expired, or you haven't configured the redirect_uri properly (check your Facebook app configuration on the Facebook dev site to set the redirect_uri).
Silhouette does log the response it gets from Facebook which should help you debug what the actual issue is, the log line to look for is in the snippet you provided:
logger.debug("[Silhouette][%s] Access token response:...
So check your logs, there you should see the response from Facebook, likely with an error indicating why they couldn't give you an access_token.

Suddenly I'm getting "Failed to obtain access token. Authorization Server reports reason: (unknown)" from Facebook

I've been using DotNetOpenAuth 3.5.0.10357 successfully for the last 2 years and TODAY I'm getting "Failed to obtain access token. Authorization Server reports reason: (unknown)" while processing facebook response.
Any ideas? Has facebook changed something today? Anyone having same issues?
public ActionResult FacebookResponse(string returnUrl)
{
IAuthorizationState authorization = facebookClient.ProcessUserAuthorization();
if (authorization == null)
{
throw new Exception("No authorization from Facebook!");
}
else
{
var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken));
Error is on facebookClient.ProcessUserAuthorization();
Thanks

Facebook Login Error PassportJS

Im using PassportJS for Facebook login in ExpressJS app. I received a recent error which didn't encountered before.
Sorry, this feature isn't available right now: An error occurred while
processing this request. Please try again later.
{
error: {
name: 'InternalOAuthError',
message: 'failedtofetchuserprofile',
oauthError: {
statusCode: 500,
data: '{
"error": {
"message": "An unexpected error has occurred. Please retry your request later.",
"type": "OAuthException",
"code": 2
}
}'
}
}
}
I don't have idea why I got the error. App ID and Key wasn't changed and sandbox was disabled.

Upload video to Facebook from the server

I have a problem when uploading videos to Facebook.
I use Facebook SDK for Android: https://github.com/facebook/facebook-android-sdk to get the access token with the following permissions: "publish_stream","email","video_upload","publish_actions"
Then I send token to the server, which should upload the video. The server tries to upload video using following code:
string fullurl = string.Format("https://graph-video.facebook.com/me/videos?title={0}&description={1}&access_token={2}", HttpUtility.UrlEncode(fileName), HttpUtility.UrlEncode(description), token);
Facebook returns an error:
System.Net.WebException: The remote server returned an error: (400) Bad Request.
at System.Net.WebClient.UploadFile(Uri address, String method, String fileName)
at System.Net.WebClient.UploadFile(String address, String fileName)
But, when I check token with the following link: https://graph.facebook.com/me?access_token=myToken Facebook returns user info. That means that token is valid. But, if this request returns error code, where I can find information about error codes?
This solution works perfectly for some users, for other users it works unstable ( 4 of 6 videos uploading failed. Facebook returns that: "connection closed by remote server"). And have not worked for some users with error: "The remote server returned an error: (400) Bad Request".
What is wrong in my code?
I've solve the problem. I have start using facebook SDK for .NET http://facebooksdk.net/ and it works for me.
Facebook.FacebookClient fb = new FacebookClient(facebookEditTask.facebookToken);
fb.PostCompleted += (o, e) =>
{
if (e.Cancelled || e.Error != null)
{
return;
}
var result = e.GetResultData();
facebookVideoUrl = CreateLinkToVideo(result.ToString());
};
dynamic parameters = new ExpandoObject();
parameters.source = new FacebookMediaStream
{
ContentType = "video/mp4",
FileName = Path.GetFileName(facebookEditTask.FilePath)
}.SetValue(File.OpenRead(facebookEditTask.FilePath));
parameters.message = fbMessage;
Task t = fb.PostTaskAsync("me/videos",
new { message = fbMessage, parameters.source });