Cannot get Facebook single signon with windows 8.1 to work - c#

After the great news about Facebook and Microsoft support Facebook SSO I have tried to implement this in a winrt/xaml/c# app for windows 8.1, however I cannot get it to work.
I have registered the app with facebook and set the app's SID in the app's settings.
This is the login code:
Uri sid = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
string callbackURL = sid.ToString();
String facebookURL = "https://www.facebook.com/dialog/oauth?client_id=" + Uri.EscapeDataString(AppId) + "&display=touch&response_type=token&scope=publish_stream&redirect_uri=" + Uri.EscapeDataString(callbackURL);
var startUri = new Uri(facebookURL);
WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri);
This will open the Facebook login dialog, I can log in, and the next dialog says "You have already authorized .
But clicking on the "Okay" or "Skip" buttons gives no response back to my app. AuthenticateAsync() never returns.
If I change the &display parameter to "touch" it works, but this is not what I want since it shows a mobile login web page not designed for this purpose.
What is wrong ?

this issue has been resolved. Can you please give this a try and let us know if you are still seeing the issue?

Yes, now it works :-)
This is the code I use, and it works fine:
Uri sid = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
string callbackURL = sid.ToString();
string facebookURL = "https://www.facebook.com/dialog/oauth?client_id=" + Uri.EscapeDataString(AppId) + "&display=popup&response_type=token&scope=publish_stream&redirect_uri=" + Uri.EscapeDataString(callbackURL);
var startUri = new Uri(facebookURL);
WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, new Uri(callbackURL));
if (result.ResponseStatus == WebAuthenticationStatus.Success && !result.ResponseData.Contains("&error="))
{
string resultString = result.ResponseData.Replace("#", "&");
AccessToken = GetQueryParameter(resultString, "access_token");
wasSuccess = true;
IsLoggedIn = true;
CurrentUser = await FacebookApi.GetCurrentUserId();
}
return wasSuccess;

Related

Google OAuth v2 for UWP

I am new to OAuth verification and I have run out of options here because when I try to access the Google's OAuth screen it never provides me with the access code. I can access the login screen and then either if I choose Allow or Deny it gives me a success message. There is no error but sometimes it gives an exception of invalid protocol but I don't know why is that.
I am trying to get help from here and also from here, but nothing is working.
The code that I am using is below:
string state = GenerateRandomBase64Url(32);
string code_verifier = GenerateRandomBase64Url(32);
string code_challenge = GenerateBase64urlencodeNoPadding(sha256(code_verifier));
string clientID = "1037832553054-2ktd0l6dop546i1ti312r2doi63sglfe.apps.googleusercontent.com";
string redirectURI = "uwp.app:/oauth2redirect";
string authorizationEndpoint = "https://accounts.google.com/o/oauth2/v2/auth";
string tokenEndpoint = "https://www.googleapis.com/oauth2/v4/token";
string userInfoEndpoint = "https://www.googleapis.com/oauth2/v3/userinfo";
string youtubeScope = "https://www.googleapis.com/auth/youtube";
string code_challenge_method = "S256";
ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
localSettings.Values["state"] = state;
localSettings.Values["code_verifier"] = code_verifier;
string authorizationRequest = string.Format($#"{authorizationEndpoint}?response_type=code&scope={Uri.EscapeDataString(youtubeScope)}&redirect_uri={Uri.EscapeDataString(redirectURI)}&client_id={clientID}&state={state}&code_challenge={code_challenge}&code_challenge_method={code_challenge_method}&login_hint={EmailBox.Text.Trim()}");
string endURL = "https://accounts.google.com/o/oauth2/approval?";
// I don't know if this is actually valid because google says that this Url is not available
Uri startURI = new Uri(authorizationRequest);
Uri endURI = new Uri(endURL);
string result = string.Empty;
try
{
//var success = Windows.System.Launcher.LaunchUriAsync(new Uri(authorizationRequest));
WebAuthenticationResult webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startURI, endURI);
switch (webAuthenticationResult.ResponseStatus)
{
// Successful authentication.  
case WebAuthenticationStatus.Success:
result = webAuthenticationResult.ResponseData.ToString();
break;
// HTTP error.  
case WebAuthenticationStatus.ErrorHttp:
result = webAuthenticationResult.ResponseErrorDetail.ToString();
break;
default:
result = webAuthenticationResult.ResponseData.ToString();
break;
}
}
catch (Exception ex)
{
result = ex.Message;
}
response.Text = result;
// the string that I get looks like this
// https://accounts.google.com/o/oauth2/approval?as=410b4db829b95fce&pageId=none&xsrfsign=AMt42IIAAAAAWO9e-l2loPR2RJ4_HzjfNiGJbiESOyoh
I don't know if this is the right way to do it in UWP apps. Furthermore the string that I get from the result is rather just a Url and it doesn't include anything that would be considered as code as described in Google examples.
So can someone point out what I am doing wrong here? This should be simple but I don't know what I am doing wrong. Thanks
I am not sure as to how I managed to solve the problem last time as my comment suggested. WebAuthenticationBroker in UWP does not work that way anymore or at least I think so. It actually asks for a startURL and a callbackURL.
I came across the same problem, as in my question, yesterday and I solved it through putting my app's redirectUri in the place of callbackURL and WebAuthenticationBroker does not throw an exception anymore and it provides a successful result.
So to solve the problem, this is how you would do it:
string redirectURI = "uwp.app:/oauth2redirect";
Uri startURI = new Uri(authorizationRequest); // as in the question
Uri endURI = new Uri(redirectUri); // change to 'redirectUri'
WebAuthenticationResult webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startURI, endURI);
switch(webAuthenticationResult.ResponseStatus)
{
case WebAuthenticationStatus.Success:
break;
}
I hope it helps someone out there. Thanks

C# Facebook app / post on site

im very new with Facebook apps and read several threads for creating them, but I have some problems with it.
First of all what I want to do: I want to create a web application that is able to post pictures, text and links on a facebook page that is managed by me.
I used the Facebook C# SDK: here!
What I have:
string facebookPageId = "<my page id>";
string app_id = "<my app id>";
string app_secret = "<my app secret>";
string scope = "publish_stream,manage_pages";
var fb = new FacebookClient();
dynamic res = fb.Get("oauth/access_token", new
{
client_id = app_id,
client_secret = app_secret,
grant_type = "client_credentials"
});
var access_token = res.access_token;
dynamic messagePost = new ExpandoObject();
messagePost.access_token = access_token;
messagePost.link = "http://www.test.at";
messagePost.name = "Testbot";
messagePost.caption = "{*actor*} " + "hello this is a test";
messagePost.description = "[SOME_DESCRIPTION]";
FacebookClient app = new FacebookClient(access_token);
app.AppId = app_id;
app.AppSecret = app_secret;
try
{
var result = app.Post("/hrechttest" + "/feed", messagePost);
}
catch (Exception e)
{
}
Well the code runs without any exceptions but in the output window I get the following:
Exception thrown: 'Facebook.FacebookOAuthException' in Facebook.dll
The next problem is:
As I understood it you must link your facebook app with your facebook page, but when I want to do that I cant select the page:
So what I did wrong or missed?
publish_stream is deprecated since many years, publish_pages is the correct permission to post to a Page (as Page).
API reference: https://developers.facebook.com/docs/graph-api/reference/page/feed#publish
Make sure you are using a Page Token, not a User Token:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
How to create Page Apps is explained in the docs too: https://developers.facebook.com/docs/pages/tabs

Login to Instagram stuck in an endless "hourglass" (WP8.1 c#)

I'm trying to integrate my app with Instagram using the following code:
string startUrl = "https://instagram.com/oauth/authorize/?client_id=" + InstagramApiKey + "&redirect_uri=http://none&response_type=token";
string endUrl = "http://none";
Uri startUri = new System.Uri(startUrl);
Uri endUri = new System.Uri(endUrl);
WebAuthenticationBroker.AuthenticateAndContinue(startUri, endUri);
and after the last line of code my app shows the Instagram login page but it's kind of stuck right before it shows me the login and password fields.
Am I missing something?
Thank you.
Your problem is in the last line is an example below
WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, **startUri, endUri**);
if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
{
}

WebAuthenticationBroker authenticate with LiveID returns Success status but no Security Token

I am using ACS to authenticate in a Windows 8 application. I am observing exactly what I expect in that the UI displays the authentication dialog and on successfully entering my LiveID credentials I am returned to my code with a Success status but I do not receive a security token, I simply get "https://XXXXX.accesscontrol.windows.net/v2/wsfederation?wa=wsignin1.0" in result.ResponseData
The code is as follows:
string loginUriString = "https://XXXXX.accesscontrol.windows.net:443/v2/wsfederation?wa=wsignin1.0&wtrealm=http%2f%YYYYY.cloudapp.net";
string redirectUriSting = "https://XXXXX.accesscontrol.windows.net:443/v2/wsfederation";
string authToken;
bool IsAuthenticated = false;
private async Task AuthenticateAsync()
{
var requestUri = new Uri(loginUriString, UriKind.RelativeOrAbsolute);
var redirectUri = new Uri(redirectUriSting, UriKind.RelativeOrAbsolute);
//var testUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
var result = await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
requestUri,
redirectUri);
if (result.ResponseStatus != WebAuthenticationStatus.Success)
throw new Exception(string.Format("Login failed : {0}", result.ResponseErrorDetail));
//authToken = ExtractTokenFromResponse(result.ResponseData);
//if (!string.IsNullOrEmpty(authToken))
//{
_client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("OAuth", result.ResponseData);
IsAuthenticated = true;
//}
}
I have seen one other SO question here with what seems like a similar problem but nothing else. Have I got something wrong?
The WebAuthenticationBroker simply keeps browsing until the next requested page is the one specified by the callbackUri parameter. At that point it returns the final URL to you so if you want to get anything back it needs to be encoded in that URL.
In the ACS control panel for the relying party you need to specify a return url that is somewhere on your site. For example https://YYYYY.cloudapp.net/federationcallback. Then create a controller to handle accept a post to that URL. The post will have a form field wresult which is some xml that will contain the token returned from ACS.
You can then send the token back to the WebAuthenticationBroker by redirecting to https://YYYYY.cloudapp.net/federationcallback/end?token={whatever you want to return}
You would then need to change the usage of the authentication broker to the following:
var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
new Uri("https://XXXXX.accesscontrol.windows.net:443/v2/wsfederation?wa=wsignin1.0&wtrealm=http%3a%2f%2fYYYYY.cloudapp.net%2f"),
new Uri("https://YYYYY.cloudapp.net/federationcallback/end")
);
// The data you returned
var token = authenticateResult.ResponseData.Substring(authenticateResult.ResponseData.IndexOf("token=", StringComparison.Ordinal) + 6);

facebook application redirects to redirect_uri location

Let me put my code first
string strSigned = Request.Params["signed_request"];
// JSONObject obj = JSONObject.CreateFromString(strSigned);
Facebook.FacebookSignedRequest fb = FacebookSignedRequest.Parse(AppSecret, strSigned);
JsonObject jsonObj = fb.Data as JsonObject;
if (!jsonObj.ContainsKey("user_id"))
{
string appId = App_Id;
string redirectUrl = "http://127.0.0.1/Default.aspx"
string redirectstr = "https://www.facebook.com/dialog/oauth?client_id=" + appId + "&redirect_uri=" + redirectUrl + "&scope=email,read_stream";
Page.ClientScript.RegisterStartupScript(this.GetType(), "redirect", "<script>top.location.href='" +redirectstr +"'</script>");
Response.Clear();
}
else
{
Response.Write(jsonObj["user_id"].ToString());
}
Above code runs perfectly untill user press allow permissions.the application is actually redirecting to the mentioned redirect_uri http:... and not staying within facebook.
i am really bugged with this.let me know the solution.
It is made this way so that it can be used by external sites which accept facebook login.
The redirect_uri can be set to:
apps.facebook.com/myapp/
or
www.facebook.com/pageurl?sk=app_YOUR_APP_ID
along with external site url.

Categories