Permission screen appears when share a message on facebook from wp8 app - c#

I need to share a message on facebook from wp8. I attached my Main.xaml screenshot.
When click share button, first login to Facebook and then ask permission for the App. I used following code.
private FacebookSession session;
private async Task Authenticate()
{
string message = String.Empty;
try
{
session = await App.FacebookSessionClient.LoginAsync("user_about_me,publish_actions,read_stream");
App.AccessToken = session.AccessToken;
App.FacebookId = session.FacebookId;
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Share/LandingPage.xaml", UriKind.Relative)));
}
catch (InvalidOperationException e)
{
message = "Login failed! Exception details: " + e.Message;
MessageBox.Show(message);
}
}
And then in Loading method of LandingPage.xaml , used following code to publish message.
private async void LandingPage_Loaded(object sender, RoutedEventArgs e)
{
FacebookClient client = new FacebookClient(App.AccessToken);
var parameters = new Dictionary<string, object>();
parameters.Add("message", "First test post using Facebook login");
await client.PostTaskAsync("me/feed", parameters);
}
When I run the App , successfully login to the Facebook, but permission screen appear as follows.
clicked ok . And then an error is occurred.
(OAuthException - #200) (#200) The user hasn't authorized the application to perform this action
I tried to solve this issue my best , but I failed . If anybody has an idea to solve this. please help me
Thank You.

I Think you are missing the Request code from your access token request.
dynamic result = facebookClient.Get("oauth/access_token", new
{
client_id = appId,
client_secret = appSecret,
grant_type = "authorization_code"
redirect_uri = Request.Url.AbsoluteUri,
code = Request["code"]
});

Related

Login with twitter to get user profile asp.net

I have a web application in asp.net . I want to use login with twiiter to get get user info. I have followed all instructions mentioned in below article
http://www.aspsnippets.com/Articles/Login-with-Twitter-in-ASPNet-using-Twitter-Button.aspx
I am getting redirected to twitter app then after authentication I am being redirected to my localhost app. Then I have check user is authorized but when I try to get user details by method FetchProfile() I am getting error.
My code is as below :
First on button click
protected void LoginTwitter(object sender, EventArgs e)
{
if (!TwitterConnect.IsAuthorized)
{
TwitterConnect twitter = new TwitterConnect();
twitter.Authorize(Request.Url.AbsoluteUri.Split('?')[0]);
}
}
then after authenticating back from twitter . on page load of application
I have check url its
http://localhost:63977/Account/Login?oauth_token=K0mECAAAAAAAxRXEAAABV44xPgc&oauth_verifier=qYLFiOlFPx4gxEu6V4AmTJG2JNjJ3nV2
then code to check
protected void Page_Load(object sender, EventArgs e)
{
TwitterConnect.API_Key = HelperClasses.TwitterApiKey;
TwitterConnect.API_Secret = HelperClasses.TwitterApiSecret;
if (Request.QueryString["oauth_token"] != null)
{
//twiiter
if (TwitterConnect.IsAuthorized)
{
TwitterConnect twitter = new TwitterConnect();
//LoggedIn User Twitter Profile Details
DataTable twitterUserDataTable = twitter.FetchProfile(); // error here
}
}
}
Tweetinvi provides a sample project doing exactly what you want to do : https://github.com/linvi/tweetinvi/tree/master/Examplinvi.Web.
I have highlighted the lines you will be interested in :
https://github.com/linvi/tweetinvi/blob/master/Examplinvi.Web/Controllers/HomeController.cs#L14-L36
You can also find more about the Authentication in tweetinvi here : https://github.com/linvi/tweetinvi/wiki/Authentication.
Here is the snippet that you want to use of ASP.NET authentication :
private IAuthenticationContext _authenticationContext;
// Step 1 : Redirect user to go on Twitter.com to authenticate
public ActionResult TwitterAuth()
{
var appCreds = new ConsumerCredentials("CONSUMER_KEY", "CONSUMER_SECRET");
// Specify the url you want the user to be redirected to
var redirectURL = "http://" + Request.Url.Authority + "/Home/ValidateTwitterAuth";
_authenticationContext = AuthFlow.InitAuthentication(appCreds, redirectURL);
return new RedirectResult(authenticationContext.AuthorizationURL);
}
public ActionResult ValidateTwitterAuth()
{
// Get some information back from the URL
var verifierCode = Request.Params.Get("oauth_verifier");
// Create the user credentials
var userCreds = AuthFlow.CreateCredentialsFromVerifierCode(verifierCode, _authenticationContext);
// Do whatever you want with the user now!
ViewBag.User = Tweetinvi.User.GetAuthenticatedUser(userCreds);
return View();
}

Get User Info after successful authentication using Windows Broker Authentication in Windows Metro App

I am working on Windows Broker Authentication.I can successfully authenticate in to the calling app and can comeback to the home page after authentication.
I am not able to get the user info (username) .I have tried but I get one message as written below.
A first chance exception of type 'System.Exception' occurred in mscorlib.dll
WinRT information: Response status code does not indicate success: 401 (Unauthorized).
Additional information: Unauthorized (401).
Response status code does not indicate success: 401 (Unauthorized).
If there is a handler for this exception, the program may be safely continued.
I have written my code below.Please friends help me.
private const string RESOURCE_NAME ="id_token";
public async Task<UserInfo> GetName(string accessToken)
{
try
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("OAuth", accessToken);
var result = await client.GetStringAsync(new Uri(loginUri));
var profileInformation =JsonObject.Parse(result).GetObject();
var name = profileInformation.GetNamedString("username");
return new UserInfo { Name = name };
}
catch (JsonException ex)
{
throw new JsonException(ex.message);
}
}
private async void btnHomeLogin_Click(object sender, RoutedEventArgs e)
{
string Scope = "openid profile";
var client = new OAuth2Client(new Uri(loginUri));
var startUri = client.CreateAuthorizeUrl(
ClientID,
RESOURCE_NAME,
Scope,
RedirectURI,
state,
nonce);
string Authresult;
try
{
var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, new Uri(startUri),new Uri(RedirectURI));
switch (webAuthenticationResult.ResponseStatus)
{
case Windows.Security.Authentication.Web.WebAuthenticationStatus.Success:
//Successful authentication.
Authresult = webAuthenticationResult.ResponseData.ToString();
UserInfo userInfo = await GetName(RESOURCE_NAME);
break;
case Windows.Security.Authentication.Web.WebAuthenticationStatus.ErrorHttp:
//HTTP error.
Authresult = webAuthenticationResult.ResponseErrorDetail.ToString();
break;
default:
//Other error.
Authresult = webAuthenticationResult.ResponseData.ToString();
break;
}
}
catch (Exception ex)
{
//Authentication failed. Handle parameter, SSL/TLS, and Network Unavailable errors here.
Authresult = ex.Message;
}
}
If you are exactly using the above code, then based on the above, you are calling GetName function with a constant string (RESOURCE_NAME) instead of the actual AuthResult (accessToken) that was returned from the webAuthenticationResult. If the intention of calling the WebAuthenticationBroker is to get back an Access Token which should later be used with HttpClient, then you need to adjust your code accordingly and make use of the right access Token when calling the HttpClient code. Otherwise the 401 is not unexpected if you are not passing the right token.

Publishing Post on Facebook C# Sdk ,Desktop Application

I am confused about publishing a post on facebook using C# sdk
I want to publish Name ,Description and photo on my page:
Do i need "publish_actions " in "items in review"(permissions)? because it is my own page .
When i try to add publish_actions ,facebook asks for privacy policy url ,How am i supposed to make it using C# Desktop Application, I didn't Found useful help on google.
Settings:
I have added http: //localhost:80/ to my site URL and:
http://abbasnaqvi512.tumblr.com/ to Valid OAuth redirect URIs.
Native or desktop app?=Yes
Is your App Secret embedded?=No
Client OAuth Login=yes
Embedded browser OAuth Login=NO
App Secret Proof for Server API calls=No
Require 2-factor reauthorization=No
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
if (e.Url.OriginalString.Contains("assets") && e.Url.OriginalString.Contains("code"))
{
code = Regex.Matches(e.Url.OriginalString, "assets.tumblr.com.*?code%3D(?<data>.*?)&")[0].Groups["data"].Value;
richTextBox1.Text += "\n\n" + code + "\n\n";
if (String.IsNullOrEmpty(code) == false)
{
webBrowser1.Stop();
webBrowser1.Dispose();
ShareOnFB();
}
}
}
catch (Exception)
{
}
}
private void ShareOnFB()
{
string pageId = "ABC";
FacebookClient client = new FacebookClient(code);
dynamic messagePost = new ExpandoObject();
messagePost.access_token = code;
messagePost.picture = "http://fc02.ostadreza-d6pkzrd.jpg";
// messagePost.link = "http://www.examplearticle.com";
messagePost.name = "NAME";
messagePost.description = "DESCRIPTION";
var result = client.Post(string.Format("/{0}/feed", pageId), messagePost);
richTextBox1.Text += "\n\n"+result+"\n\n";
}
Rightnow it is giving me Error
"Malformed access token AQA44CIJCyoV7_Xlz3mtvdPErPBrmtF6ykz6teCc9QINrfePHxEOiQKIyl8wgxH1mvQxEtLE-xnVfdyfiE38eA2M1YU7RS22MNIKNUh5wMmd2zwPCLj30PiEaq6CKIfcq9yIvq_slblOWmE4LYcynyH_pJuZcPc3EqLCQoCUBtSO58X1WtiohRoRvq70QWHpZec-7jhzUQnW75nlk4wpEwcJ9yOcBlPbne72sV6yX_hqndI5RKVDjqRJzdOscOblbLCkC1xtI0rMD1bCJufvpAa-tMsIyG6ATqrk6TNqXXASlcvialbzh0WttS2x-j_J59LF7cBh22T18P8qOly5cOwF"
Thanks for reading my question ,Kindly help me,
Update: I have added publish_actions in review by adding tumblr privacy policy url ,Notes and screen shots of my application ,It is on review

DotNetOpenAuth Google API Offline Access

I've spent some time over the last few days trying to implement a feature for my web application. The feature should add new events to a users google calendar while they are offline. I read the Google OAuth2 documentation for web server applications and seem to understand the basics of it. I created a link to authorize the application for offline access:
<a target='_blank' href='https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Ftasks&response_type=code&client_id=<MY CLIENT ID>&access_type=offline&redirect_uri=http%3A%2F%2Flocalhost:49949%2Foauth2callback.aspx'>Grant Tasks Permission</a>
If the user accepts then I capture the refresh token at the redirect uri like this:
private static OAuth2Authenticator<WebServerClient> _authenticator;
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.Request["code"] != null)
{
_authenticator = CreateAuthenticator();
_authenticator.LoadAccessToken();
}
Response.Write("Refresh Token: " + _authenticator.State.RefreshToken);
}
private OAuth2Authenticator<WebServerClient> CreateAuthenticator()
{
var provider = new WebServerClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = "<MY CLIENT ID>";
provider.ClientSecret = "<MY CLIENT SECRET>";
return new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization);
}
private IAuthorizationState GetAuthorization(WebServerClient client)
{
return client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request));
}
For testing purposes I have been copying the refresh token to a text file for further use.
My problem is using this refresh token for offine access. I have been using this code to refresh the token:
protected void btnGetTasks_Click(object sender, EventArgs e)
{
if (_service == null)
{
_authenticator = CreateAuthenticator();
_service = new TasksService(new BaseClientService.Initializer() { Authenticator = _authenticator });
}
var cl = _service.Tasklists.List().Fetch();
}
private OAuth2Authenticator<WebServerClient> CreateAuthenticator()
{
// Register the authenticator.
var provider = new WebServerClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = "<MY CLIENT ID>";
provider.ClientSecret = "<MY CLIENT SECRET>";
var authenticator = new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization);
return authenticator;
}
private IAuthorizationState GetAuthorization(WebServerClient client)
{
string scope = "https://www.googleapis.com/auth/tasks";
IAuthorizationState state = new AuthorizationState(new[] { scope });
state.RefreshToken = "<REFRESH TOKEN FROM FIRST STEP>";
var result = client.RefreshToken(state);
return client.ProcessUserAuthorization();
}
Everything seems fine at this point. When I step through the code I can see the result from client.RefreshToken(state) is true. The issue is when I call this line of code:
_service.Tasklists.List().Fetch();
It returns a (401) unauthorized error from google. I'm looking into the cause but I am not sure how to proceed and I am running short on time with this feature. Any advice would be greatly appreciated. Thanks!
Seems just the act of putting code on here always helps me figure it out a little sooner :)
It now appears this line is unnecessary:
return client.ProcessUserAuthorization();
removing that from the GetAuthorization method and just returning the state passed to RefreshToken has resolved the unauthorized error. I'll leave the question in case it stumps anyone else.

"The post's links must direct to the application's connect or canvas url"?

I'm building an application for WP7 using the Facebook C# SDK. When I attempt to post a message to a users wall (Just a plain message) everything works fine. But when I attempt to post a link to the users wall I get this exception message:
(OAuthException) (#100) The post's links must direct to the application's connect or canvas URL.
Does anyone know how to fix this? I have heard of canvas applications but I didn't think this applied to a phone app. Perhaps this is a setting on Facebook?
Any feedback is appreciated.
Here is the code I used to post to facebook:
private void button1_Click(object sender, RoutedEventArgs e)
{
_fbClient.PostCompleted +=
(o, er) =>
{
if (er.Error == null)
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show(er.Error.Message);
}
};
var args = new Dictionary<string, object>();
args["name"] = "Hello World!!";
args["link"] = "http://www.nfl.com";
args["caption"] = "";
args["description"] = "";
args["picture"] = "";
args["message"] = "Hello World from application.";
args["actions"] = "";
FacebookAsyncCallback callback = new FacebookAsyncCallback(this.postResult);
_fbClient.PostAsync("me/feed", args, callback);
}
private void postResult(FacebookAsyncResult asynchResult)
{
MessageBox.Show("Success");
}
NOTE: If I remove the string from "link" it works.
I found a solution to my problem "here". In your app settings within Facebook you have to set "Stream Post Url Security" to false. Hope this helps someone.
Go to the Facebook App. Edit its settings. On the Advanced settings page, disable the "Stream post URL security" option.

Categories

Resources