Trouble getting test user information - c#

I'm trying to use the Facebook SDK 5.2.1 to ultimately create a test user, however even what I believe is the simple example of getting the list of test accounts isn't working for me. I get the OAuthException "An access token is required to request this resource."
Here's my code (replace APP ID and APP SECRET with my own):
FacebookOAuthClient oauth = new FacebookOAuthClient { AppId = "APP ID", AppSecret = "APP SECRET" };
dynamic tokenRes = oauth.GetApplicationAccessToken();
fbClient = new FacebookClient(tokenRes.access_token);
dynamic response = fbClient.Get("APPID/accounts/test-users");
However, I get the exception on the fbClient.Get line.
Any idea as to what's wrong?
Thanks,
Chad

After hours of trying various things and reading various web pages/blogs, I found the reason it wasn't working. In my app settings, I had my app type set to a Native/Desktop App. Changing this to Web, allows the above scenario to work. I'm not yet quite sure of what other differences exist between web vs native facebook apps. My app is certainly only being used via a desktop application and I can't understand why I need to set this to Web just to allow me to create test users.

This code works in my app:
var app = new FacebookClient(FacebookApplication.Current.AppId,
FacebookApplication.Current.AppSecret);
dynamic result = app.Post(string.Format("{0}/accounts/test-users",
FacebookApplication.Current.AppId),
new { installed = true, permissions = "user_about_me" });

The reason why you are receiving the exception OAuthException is because you have not yet got the permission of the user.
To do a Graph API call on the current user, you need to get the user to accept the permissions that you require FIRST and then do the Graph API call.
You need to get the user to a browser some how in your application, as there is not an authentication flow which doesn't require a browser window.
Check out this URL to view the authentication flows:
http://developers.facebook.com/docs/authentication/

Related

Azure mobile service auto-login with Xamarin

I'm brand new to Xamarin and playing around with a simple cross-platform app.
The app connects to an Azure Mobile Service, and requires login which I've set up server-side following tutorial: and client-side following tutorial.
Everything works fine! However, the current implementation requires you to login everytime you start the app. How can i cache the user credentials and auto-login as long as you don't log out?
I've tried something like this, but obviously didn't work:
When a user is logging in I save (I'm not calling directly to MobileServiceClient, just showing you a snippet):
var userId = MobileServiceClient.CurrentUser.UserId;
var authToken = MobileServiceClient.CurrentUser.MobileServiceAuthenticationToken
So i store these two strings, and when I next time open the app I try to:
CurrentClient.CurrentUser = new MobileServiceUser(userId);
CurrentClient.CurrentUser.MobileServiceAuthenticationToken = authToken;
As I said this does not seem to be the correct way since it does not work. What is the correct way to cache and auto-login an user?
You need to move over to a CLIENT-FLOW - in client-flow authentication, you use the client SDK provided by the auth provider and then pass that token silently to Azure Mobile Apps to authenticate there. Check out Chapter 2 of my book - http://aka.ms/zumobook

Azure AD: user_interaction_required issue when authenticating a native application

I have Exchange Online from Office 365 with a mailbox and I need to access this mailbox with my console C# application that uses Managed EWS. The requirement is that the console application should use OAuth authentication to access the Exchange Online.
I have Azure AD set up, and created an application there, received clientid and redirect uri. I have given full permissions to the application - please have a look at the screenshot below:
I'm using Active Directory Authentication Library for .NET (latest version from NuGet) to issue a token, but having a problem to get it running...
My code is:
AuthenticationContext authenticationContext = new AuthenticationContext("https://login.windows.net/rsoftgroup.onmicrosoft.com", false);
AuthenticationResult authenticationResult = null;
try
{
var authenticationTask = authenticationContext.AcquireTokenAsync(
"outlook.office365.com",
"c4fa7d60-df1e-4664-a8f8-fb072d0bb287",
new Uri(redirectUri),
new PlatformParameters(PromptBehavior.Never)
);
authenticationTask.Wait();
authenticationResult = authenticationTask.Result;
exchangeService.Credentials = new OAuthCredentials(authenticationResult.AccessToken);
}
catch (AdalException)
{
// Exception occured on the authentication process.
}
I get AdalException with message: "user_interaction_required: One of two conditions was encountered: 1. The PromptBehavior.Never flag was passed, but the constraint could not be honored, because user interaction was required. 2. An error occurred during a silent web authentication that prevented the http authentication flow from completing in a short enough time frame"
Can somebody help me how to solve it?
I need the OAuth authentication to work without user interaction, as this will be a command line application...
Any suggestions highly appreciated.
Your application still needs to authenticate as some user, currently if you look at your code you don't authenticate because of PromptBehavior.Never and you don't specify any user-credentials and use the implicit auth flow eg http://www.cloudidentity.com/blog/2014/07/08/using-adal-net-to-authenticate-users-via-usernamepassword/
For a standard Console apps where you are going to authenticate (eg ask for credentials when the app is run) I would use out of band call urn:ietf:wg:oauth:2.0:oob (you then don't need a redirection endpoint) and set your code to prompt eg
AuthenticationContext ac = new AuthenticationContext("https://login.windows.net/Common");
var authenticationTask = ac.AcquireTokenAsync(
"https://graph.windows.net",
"5471030d-f311-4c5d-91ef-74ca885463a7",
new Uri("urn:ietf:wg:oauth:2.0:oob"),
new PlatformParameters(PromptBehavior.Always)
).Result;
Console.WriteLine(authenticationTask.AccessToken);
When you run the Console app windows and the ADAL library will handle the plumbing and show the correct authentication prompts and get the Token back and you get the benefits of reduce attack surface over prompting for the credentials yourself in your code (or as parameters etc)
As Venkat comments suggests if you don't need to use EWS (eg no existing code base investment etc) then using the REST endpoints maybe a better solution if your building a daemon type application as you can take advantage of this type of auth flow eg https://blogs.msdn.microsoft.com/exchangedev/2015/01/21/building-daemon-or-service-apps-with-office-365-mail-calendar-and-contacts-apis-oauth2-client-credential-flow/

DropNet DropBox login, how to do it programmatically in a console application?

Question:
I'm using a DropBox csharp API from here:
https://github.com/dkarzon/DropNet
From the Unit tests, and the only working sample from here
https://github.com/dkarzon/DropNet/blob/master/DropNet.Samples/DropNet.Samples.Web/Default.aspx.cs
I figured that it works like this:
DropNet.DropNetClient client = new DropNet.DropNetClient(strApiKey, strAppSecret);
DropNet.Models.UserLogin login = client.GetToken();
client.UserLogin = login;
var accountInfo = client.AccountInfo();
str = accountInfo.quota_info.quota.ToString();
The probem is, it throws an exception on accountinfo. (System.Net.HttpStatusCode.Unauthorized)
Everything before works fine, I get the login (usertoken & usersecret) .
I think my problem is this part of the sample application:
var url = _client.BuildAuthorizeUrl(Request.Url.ToString() + "?dropboxcallback=1");
Response.Redirect(url);
Where it redirects to dropbox for a login...
I don't have a web application, so I have no URL...
What I have is a console application, that should make a backup of my database every evening automatically as a service, for which it certainly is very bad requiring a webbrowser and a user which has to type in email/username + password.
How can I do a login by directly supplying the hardcoded username and password ?
If I use the sample application, then it works, but that requires typing in the username and password on the web, and that sucks big time for a console application...
As far as I know from other API's (facebook, google, stack exchange etc.) you'll have to redirect your user to a webpage of Dropbox, where it will grant permissions to you to use it's account to perform things.
So in general it is not possible to achive this without a webbrower. Otherwise you'll have to perform really dirty hacks to hack arround the permission system of dropbox.
Please have a look at "OAuth 2.0 authorization flow" on google.
Here's a diagram I found at Yahoo which show's how it works:
For uisng the DropnetClient's 4 argument constructor also we need to build web based url and allow the user to authenticate his account this is compusory thing, accesstoken will generate after the user hit allow button in authentication process
As GameScripting explained the Dropbox API uses oauth which requires user login through the dropbox website to authenticate the access tokens.
Checkout the documentation here: http://dkdevelopment.net/what-im-doing/dropnet/ for the 3 step process.
What sort of application are you building? Normal process is to load a browser control inside the application and navigate to the login URL with it.
Also have a look at the sample Windows Phone app to give you an idea of how this process works: https://github.com/dkarzon/DropNet/blob/master/DropNet.Samples/DropNet.Samples.WP7/MainPage.xaml.cs
Instead of hardcoding the username and password, you can hardcode the OAuth access token.
First, create a simple program (using the same app key) that follows the standard browser-based authorization flow. Then use it to authorize the app with the desired user. This will give you an OAuth access token (a "token" and "token secret") associated with that user and your app key.
Then, in your service-style application, just hardcode the OAuth access token (using DropNetClient's 4-argument constructor).
It is possible, using SharpBox - tested, works.
One needs to acquire the AccessToken as a one-time-action manually, then after that, one can omit the login page and use the saved AccessToken.
http://www.jayway.com/2012/02/06/unboxing-dropbox-and-sharpbox-2/
The magic line is:
Globals.DropBox.Token = AppLimit.CloudComputing.SharpBox.StorageProvider.DropBox.DropBoxStorageProviderTools
.ExchangeDropBoxRequestTokenIntoAccessToken(
Globals.DropBox.config
, Globals.DropBox.AppKey, Globals.DropBox.AppSec
, Globals.DropBox.requestToken
);

AuthenticationToken is null

I'm currently writing a C# metro app for the Windows 8 consumer preview which fetches some data from my REST-based web services. I want the app to authenticate against the services using the Windows Live account of the current user. Therefore, I added the Windows Live SDK to my solution and pasted the following snippet from the documentation into my login view:
LiveAuthClient liveClient = new LiveAuthClient();
LiveLoginResult loginResult = await liveClient.Login(new string[] { "wl.signin" });
After the login call has succeeded, I want to pass the encrypted AuthenticationToken of the LiveConnectSession via SSL to my webservice which should decrypt the token and read the information it is interested in (that's what the documentation suggests for such a SSO scenario). But sadly, the AuthenticationToken property of the session is always null. Am I missing something here?
I ran into the same problem and realised I had two issues with my configuration:
I didn't have a "Redirect domain" defined in the API settings of https://manage.dev.live.com
I wasn't using the overloaded LiveAuthClient constructor
For example in the API settings you specify:
Redirect domain: http://localhost/myapp
You then use the constructor overload of the LiveAuthClient:
var authClient = new LiveAuthClient("http://localhost/myapp");
var loginResult = await authClient.LoginAsync("wl-signin");
//this should no longer be null
var authToken = loginResult.Session.AuthenticationToken;
The redirect URI doesn't need to point to a working endpoint from what I can tell, as long as the two values match you should be in business.
Have you registered your app on the Live Connect app management site for Metro style apps? You need to register it here for it to work with Live Services. It will give you following instructions after you have given the app package a name and publisher.

facebook c# sdk getting started

I would like to write a console application that automatically posts information to my wall once every morning.
I have signed up for facebook developer and have a AppID and App Secret
I have been trying to play with the C# facebook SDK and looked through several examples.
Seems like the examples get a user token - but have to use a browser that is in windows forms. This is an automated process - so I dont want to have a user present.
Ive also created some examples using the application token - but it does not seem to be able to write to the wall.
I wrote the Twitter equivalent very quickly. I must be missing something here ???
What is the proper way to proceed?
It seems that all I should need to is:
FaceBookClient(appID, appSecret)
and then just
FaceBookClient.Put(message)
???
clarification added:
Playing with the C# facebook sdk winform application
I had to change their FacebookLoginDialog.cs to use the folling URL:
https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=APPID&client_secret=APPSECRET&scope=user_about_me,publish_stream,offline_access
which returns an accesskey in WebBrowser.DocumentText
If I then call:
var fb = new FacebookClient(_accessToken);
dynamic parameters = new ExpandoObject();
parameters.message = "Hello World!";
dynamic result = fb.Post("me/feed", parameters);
I get the exception:
(OAuthException) An active access token must be used to query information about the current user.
If I change the code above to NOT use that access token - but use the appID and Appsecret:
FacebookClient myFacebookClient = new FacebookClient("APPID", "APPSECRET");
dynamic parameters = new ExpandoObject();
parameters.message = "Hello World!";
dynamic result = myFacebookClient.Post("me/feed", parameters);
Then I get the exception:
(OAuthException) An active access token must be used to query information about the current user.
I guess it is the same exception
Here is what I found.
Download the facebook C# sdk source code and samples from http://facebooksdk.codeplex.com/
Unzip the code and load into Visual Studio the Facebook C# SDK sample called CS-WinForms.
At the top of Form1.cs - enter your application ID
Run the application.
Form1.cs pops up with a button "Login to Facebook". Click the button.
FacebookLoginDialog.cs pops up with a browser window in it displaying facebook asking for permissions.
FacebookLoginDialog.cs creates a browser window that will go to your user on facebook and request permissions. By default those permissions are: user_about_me,publish_stream,offline_access.
Offline_access means the AccessToken you get - never expires
Click "OK" in Facebook to allow the application to access your facebook data.
FacebookLoginDialog.cs should find that you logged in and get the access token that never expires.
The access token is a string.
Insert a break point so that you can copy this access token. Save this access token as you can use it from now on to access to Facebook.
Facebook developers website has some tools that you can use to check the access token
https://developers.facebook.com/tools/debug/access_token
You can enter your access token and click "Debug" and it should list your applicationID, UserID, and for "expires" it should say "never".
Once you have this access token - then you can simply write code like:
var fb = new FacebookClient(AccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = FacebookString;
dynamic result = fb.Post("me/feed", parameters);
var id = result.id;
to post message to Facebook!
You should request offline_access in addition to publish_stream. Once you have the never-expiring token, store that in your app.

Categories

Resources