I have a mirror api app, and authorised users via outh and saved their access token and refresh token in database for offline use. Now I want to add timeline item to those users offline (using saved access token and refresh token).
Here is my code,
String accessToken = db.getAccessToken();
String refreshToken = db.getRefreshToken();
BatchRequest batch = MirrorClient.getMirror(null).batch();
BatchCallback callback = new BatchCallback();
TimelineItem notifyTimelineItem = new TimelineItem();
notifyTimelineItem.setHtml(ZONE_HTML);
Credential userCredential = AuthUtil.getCredential(userUniqueId);
userCredential.setAccessToken(accessToken);
userCredential.setRefreshToken(refreshToken);
MirrorClient.getMirror(userCredential).timeline().insert(notifyTimelineItem).queue(batch, callback);
batch.execute();
Here am getting error like Failed to insert item, user need to login . How can I add timeline item in offline?
Actually I got userCredential as null. So I used below code and it works fine.
String accessToken = db.getAccessToken();
Mirror service = new Mirror.Builder(new NetHttpTransport(), new GsonFactory(), null).setApplicationName("GOauthAndroid").build();
TimelineItem timelineItem = new TimelineItem();
timelineItem.setHtml(DANGER_ZONE_HTML);
timelineItem.setNotification(new NotificationConfig().setLevel("DEFAULT"));
try {
service.timeline().insert(timelineItem).setOauthToken(newAccessToken).execute();
} catch (IOException e) {
e.printStackTrace();
}
Related
I am trying to do the Dataset refresh for a PowerBI Report. I created the gateway and I am able to do the dataset refresh from the admin portal. I could validate that the refresh happend successfully from UI i.e. Last Refresh column in the Admin portal. But when I try to do the refresh from a C# webapi code, I am getting the below mentioned error.
Error Message:
The remote server returned an error: (401) Unauthorized.
Stack Trace:
at System.Net.HttpWebRequest.GetResponse()
at BlueSkyPowerBIService.Controllers.PowerBIController.<RefreshDatasetsForReports>d__13.MoveNext() in C:\Krishnan\RSI\SourceCode\Bluesky Developement\BlueSky Development\BlueSkyPowerBIService\BlueSkyPowerBIService\Controllers\PowerBIController.cs:line 258
Before the refresh code, I am able to do the authentication agains the Azure AD and it succeeds and generated the auth token, but when it call the API to refresh it crashes with the above said error.
Please find my code which i am use for data refresh
List<ReportDetails> reportDetailsList = new List<ReportDetails>();
var result = new EmbedConfig();
ReportDetails reportDetails = new ReportDetails();
try
{
result = new EmbedConfig { Username = username, Roles = roles };
var error = GetWebConfigErrors();
if (error != null)
{
result.ErrorMessage = error;
//return View(result);
return null;
}
var credential = new UserPasswordCredential(Username, Password);
var authenticationContext = new AuthenticationContext(AuthorityUrl);
var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);
if (authenticationResult == null)
{
result.ErrorMessage = "Authentication Failed.";
//return View(result);
return null;
}
var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");
// Create a Power BI Client object. It will be used to call Power BI APIs.
using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
{
// Get a list of reports.
var reports = await client.Reports.GetReportsAsync();
for (int index = 0; index < reports.Value.Count; index++)
{
reportDetails = new ReportDetails();
Report report = reports.Value[index];
HttpWebRequest request;
if (report.Id == "6317f207-57d3-4f5f-9644-18bfbb9bef99")
{
var url = "https://api.powerbi.com/v1.0/myorg/groups/{0}/datasets/{1}/refreshes";
request = System.Net.HttpWebRequest.CreateHttp(String.Format(url, GroupId, report.DatasetId));
request.KeepAlive = true;
request.Method = "POST";
request.ContentLength = 0;
request.Headers.Add("Authorization", String.Format("Bearer {0}", authenticationResult.AccessToken));
using (Stream writer = request.GetRequestStream())
{
var response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Dataset refresh request{0}", response.StatusCode.ToString());
}
}
}//end for(int index=0; index< reports.Value.Count; index++)
return reportDetailsList;
}
}
catch (HttpOperationException exc)
{
result.ErrorMessage = string.Format("Status: {0} ({1})\r\nResponse: {2}\r\nRequestId: {3}", exc.Response.StatusCode, (int)exc.Response.StatusCode, exc.Response.Content, exc.Response.Headers["RequestId"].FirstOrDefault());
}
catch (Exception exc)
{
result.ErrorMessage = exc.ToString();
}
I have granted all the required permissions in Azure portal under App Registrations,
Any ideas why I am getting this error? How to fix this issue?
This looks like a wrong configuration on the permissions of the Azure Active Directory application you are using to perform the refresh. As shown here we need to register a native app and declare some permissions to be able to access the Power BI rest API.
You need to make sure that this app has the Dataset.ReadWrite.All permission. You can see and even change permissions of the application in Azure portal under Azure Active Directory -> App Registrations. If you can't see the application select All apps from the drop down on the right.
This is how our application looks like that we are using successfully to perform a refresh through the rest API
I am trying to authenticate my user in a Xamarin Forms cross platform app using AWS Cognito User Pools.
I am able to sign up a user using the SignUpAysnc() and I can see it populate in the user pool in the AWS console.
CognitoUserPool userPool = AmazonUtils.UserPool;
Dictionary<string, string> userAttributes = new Dictionary<string, string>();
userAttributes.Add("email", email);
userAttributes.Add("given_name", given_name);
userAttributes.Add("family_name", family_name);
userAttributes.Add("gender", gender);
userAttributes.Add("birthdate", birthdate);
userAttributes.Add("address", address);
userAttributes.Add("locale", locale);
userAttributes.Add("phone_number", phone_number);
await userPool.SignUpAsync(email, Password, userAttributes, null);
However when I try to use the email and password provided to sign in I keep getting this exception:
[0:] Missing Authentication Token
My current authentication code is:
private async void LoginButton_Clicked(object sender, EventArgs e)
{
AdminInitiateAuthRequest authRequest = new AdminInitiateAuthRequest();
authRequest.ClientId = Constants.ClientID;
authRequest.AuthParameters.Add("email", "test.user#email.com");
authRequest.AuthParameters.Add("password", "Password12!");
authRequest.UserPoolId = Constants.AuthPoolID;
authRequest.AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH;
try
{
AdminInitiateAuthResponse response = await AmazonUtils.IdentityClientProvider.AdminInitiateAuthAsync(authRequest);
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
Does anyone know what I might be missing?
The thing is that you need to initiate the authentication challenge first, and then pass password as well as encrypted string, that contains pool name, username, secret block and other information.
This is a good .Net example: http://blog.mmlac.com/aws-cognito-srp-login-c-sharp-dot-net/
Note that you need to add Org.BouncyCastle.Math and Org.BouncyCastle.Security via NuGet to your project in order to compile it.
There is another example: https://gist.github.com/dbeattie71/44ea3a13145f185d303e620c299ab1c5
It looks promising, but I did not check it so I can't guaranty that it works. From it you could get an understanding on how overall process looks like.
The situation:
I have a website and creates "posts". As a new post is created I want to send the new post to my facebook pages feed. I have all of the code down to do this and it works fine as long as I get an access token from the graph API explorer tool. This is not going to work as it expires after about an hour. When I generate the access token from code, it appears that it is a app access token and it does not give me access to my page. So the big question is how do I obtain a user access token from code that will have access to post to my page.
Here is how I am getting the access token.
private static string GetApiAccessToken()
{
var client = new FacebookClient();
dynamic result = client.Get("oauth/access_token", new
{
client_id = SessionGetter.Instance.FacebookApiKey,
client_secret = SessionGetter.Instance.FacebookSecretKey,
grant_type = "client_credentials",
scope = "manage_pages"
});
return result.access_token;
}
Then I use the access token to try and get the Page access token and this is where it tells me that I don't have authorization and all I get back in the dictionary is an "id".
private static string GetPageAccessToken(string accessToken, string pageId)
{
try
{
var fb = new FacebookClient(accessToken);
var parameters = new Dictionary<string, object>();
parameters["fields"] = "access_token";
var result = (IDictionary<string, object>)fb.Get(pageId, parameters);
var pageAccessToken = (string)result["access_token"];
return pageAccessToken;
}
catch (FacebookApiException ex)
{
}
return null;
}
Now like I said, if I use the access token from the graph explorer, the code works fine.
Then the post is made to the graph API
var facebookClient = new FacebookClient(pageAccessToken);
var result = (IDictionary<string, object>)facebookClient.Post("me/feed", new Dictionary<string, object>
{{"message",postMessage}, {"picture", csLogo},
{"link", LinkHelper.AssignmentUrl(wrapper.Assignment)}});
Make sure the user access token has manage_pages extended permissions.
then make a request to me/accounts to the get the page access token.
Then post to {pageid}/feed using the page access token.
So I have an app set up, and I'm trying to send scores via a server rather than from the application. This allows me to keep scores longer term, whilst also having the social advantages of Facebook.
Now, the problem I have comes in retrieving the scores using the Application Token. I can post absolutely fine using either the Application Token or a User Token, but when retrieving the scores with the Application Token I receive the following:
{
"data": [
]
}
If it was flat out not working or a permissions issue I'd expect to receive an error returned, but the fact it returns an empty array is puzzling. More puzzling is that using a User Access Token retrieves the score absolutely fine, so it's clearly arriving correctly into the Facebook backend.
Is this just a problem with using an App Access Token in this situation? The documentation says that I should be able to use one, but maybe it's mistaken?
I'd also like to clarify that I've run this both in code and via the Graph Explorer, always with no success.
Make sure that you have granted user_games_activity and friends_games_activity permissions
on developers.facebook.com/tools/explorer
from above link you will get an application access_token and add it in your code like this
public void sendDataToFacebookGraphServer()
{
// TODO Auto-generated method stub
final Session session = Session.getActiveSession();
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(UnityPlayer.currentActivity, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://graph.facebook.com/user_id/scores");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("score", "3000"));
// add this line and try
pairs.add(new BasicNameValuePair("access_token", "add_app_access_token_here"));
try{
post.setEntity(new UrlEncodedFormEntity(pairs));
}
catch(UnsupportedEncodingException e)
{
}
try{
response = client.execute(post);
Log.i("*********Response*******************************************************", response.toString());
UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(UnityPlayer.currentActivity,""+response.toString(),Toast.LENGTH_LONG).show();
}
});
}
catch (IOException e1)
{
}
}
Is this supposed to work with the app access token? I don't think it is.
According to the Scores Documentation you can
Retrieve a user's score with the user or app access token (/USER_ID/scores)
Retrieve a user's friends' scores for your app with the user access token (/APP_ID/scores)
Retrieve a user's friends' scores in any app with the user access token (/USER_ID/scores) - though this one respects those users' privacy settings so you won't get an answer for users whose game/app activity is private
i'm attempting to provide a facility on my site that allows a user to create a facebook event for their booking.
http://developers.facebook.com/docs/reference/api/event/
now im doing the correct process:
1) first getting authorisation from the user
https://graph.facebook.com/oauth/authorize?client_id=APP_ID&redirect_uri=http://urlimredirectingto.comtype=web_server
2) requesting for an access token with the "code" that is returned in step 1
https://graph.facebook.com/oauth/access_token
3) using the access_token to create the event ...
string facebookCreateUri = string.Format("https://graph.facebook.com/{0}/events", loggedInMember.FacebookUID);
var formData = new HttpUrlEncodedForm()
{
{"access_token", accessToken},
{"owner", loggedInMember.FacebookUID},
{"description", "nice event that should be on the owners wall"},
{"name", "event on the users wall"},
{"start_time", "1272718027"},
{"end_time", "1272718027"},
{"location", "rochester"},
{"privacy","OPEN"}
};
HttpContent content = HttpContent.Create(formData);
HttpClient client = new HttpClient();
var response = client.Post(facebookCreateUri, "application/x-www-form-urlencoded", content);
but the event is posted on my app's wall, not the user's wall. It shouldn't have anything to do with the authentication/access_token elements because i use the same process to post on the user's wall. (http://developers.facebook.com/docs/reference/api/status/) and that works just fine.
I came back with a solution, after a week of working at many features with Facebook SDK, it finally works!
protected void onPostEvent(object sender, EventArgs e)
{
if (CanvasAuthorizer.Authorize())
{
var fb = new FacebookWebClient(CanvasAuthorizer.FacebookWebRequest);
dynamic parameters = new ExpandoObject();
parameters.description = txtEvDett.Text;
parameters.name = txtEvName.Text;
parameters.start_time = DateTime.Now.ToString("yyyyMMdd");
parameters.end_time = DateTime.Now.AddDays(1).ToString("yyyyMMdd");
parameters.access_token = CanvasAuthorizer.FacebookWebRequest.AccessToken;
dynamic eventDet = fb.Post("me/events", parameters);
litEvent.Text = String.Format("You have created the event with ID: {0}", eventDet.id);
lnkEvent.Visible = true;
lnkEvent.NavigateUrl = String.Format("http://www.facebook.com/event.php?eid={0}", eventDet.id);
}
}
For events, you have to request the create_event permission.
You should use /me/events to post on your events.
I user the C# SDK for Facebook from Codeplex - last version available for dld (aug 2011 - v5.2.1).
Good luck!
I don;t see in your request for Authorization any permission.. base permissions are not enough to do the postings.
i used:
https://www.facebook.com/dialog/permissions.request?app_id=MY_APP_ID&next=MY_APP_URL&display=page&response_type=code&canvas=1&perms=publish_stream,user_about_me,email
This is in the context of a canvas app. where MY_APP_URL is the url from facebook of the app:
http://apps.facebook.com/MY_APP_NAME_OR_ID
See extended permissions for events and check event's page in documentation
[EDIT] - I came back, sorry, now i did a test, and indeed, it works for me, but only of i post on my app's wall; even if i provided the 'user_events' permission i get this error:
The remote server returned an error: (403) Forbidden when posting on a user's wall.
This being said, i also subscribe to this question.