facing problem in facebook connect api using asp.net - asp.net

I am using Facebook connect API to grab my friendlist. It redirects me to the login page.
but when I provide credentials it throws an error something like this;
API Error Code: 100
API Error Description: Invalid parameter
Error Message: Requires valid next URL.
Here is the code;
//my actual values are mentioned in the key
_fbService.ApplicationKey = "KEY";
_fbService.Secret = "Key";
_fbService.IsDesktopApplication = false;
string sessionKey = Session["Facebook_session_key"] as String;
string userId = Session["Facebook_userId"] as String;
// When the user uses the Facebook login page, the redirect back here will will have the auth_token in the query params
string authToken = Request.QueryString["auth_token"];
if (!String.IsNullOrEmpty(sessionKey))
{
_fbService.SessionKey = sessionKey;
_fbService.UserId = userId;
}
else if (!String.IsNullOrEmpty(authToken))
{
_fbService.CreateSession(authToken);
Session["Facebook_session_key"] = _fbService.SessionKey;
Session["Facebook_userId"] = _fbService.UserId;
Session["Facebook_session_expires"] = _fbService.SessionExpires;
}
else
{
Response.Redirect(#"http://www.Facebook.com/login.php?api_key=" + _fbService.ApplicationKey + #"&v=1.0");
}
if (!IsPostBack)
{
// Use the FacebookService Component to populate Friends
//MyFriendList.Friends = _fbService.GetFriends();
MyFriendlist.Friends = _fbService.GetFriends();
}
Does anyone knows how to get rid of this?
Thanks in advance.

Instead of redirecting to the url, try using
base.login=true;
//Response.Redirect(#"http://www.Facebook.com/login.php?api_key=" + _fbService.ApplicationKey + #"&v=1.0");
or
Response.Redirect(#"http://www.Facebook.com/login.php?api_key=" + _fbService.ApplicationKey + #"&v=1.0&next=http://apps.facebook.com/yourapplication");

Related

I receive {"code":"rest_forbidden","message":"Sorry, you are not allowed to do that.","data":{"status":401}} when trying to retrieve a private post

Trying to retrieve a post using the REST API:
http://localhost/mysite/wp-json/wp/v2/posts/605.
I am authenticated as administrator and the post was published my me. I have all the administrator rights assigned. I can retrieve non-private posts but as soon as I mark them private I get an error as a response
{"code":"rest_forbidden","message":"Sorry, you are not allowed to do that.","data":{"status":401}}
Is there anything else I should be doing to allow retrieval of private posts ?
-- Edit: I am authenticated via JWT but my response returns all public posts and none of the private ones
if (await client.IsValidJWToken())
{
var queryBuilder = new PostsQueryBuilder();
queryBuilder.PerPage = 8;
queryBuilder.Page = 1;
queryBuilder.Embed = true;
//queryBuilder.Categories = new int[] { category };
queryBuilder.Statuses = new Status[] { };
try
{
var response = await client.Posts.Query(queryBuilder);
var r = response;
}
catch (Exception e)
{
var m = e.Message;
}
I think this is the expected behavior [at least I can confirm the same thing on my sites]. You'll probably have to create your own route to access the private posts.

OneDrive for Business :"invalid_request","error_description":"AADSTS90014: The request body must contain the following parameter: 'grant_type

I'm trying to integrate the OneDrive for Busines to a Web Form App.
For this I use the documentation given at this url
In web Form App I have two Pages:
First one is Login page which have a button for login
On login button click I create a GET Request to OneDrive for Business API using the following code:
HttpClient client = new HttpClient();
Redirecturi = Uri.EscapeDataString(Redirecturi);
string url = string.Format("https://login.windows.net/common/oauth2/authorize?response_type=code&client_id={0}&redirect_uri={1}", ClienId, Redirecturi);
var response = client.GetAsync(url);
var json = response.Result.Content.ReadAsStringAsync();
Label2.Text = json.Result;
When I click the login button it takes me to micorosoft login service and sends me back to callback.aspx page with access code (Redirect URI configured on azure)
I got the access code.
On the second page I redeem the access code and make a POST request to get the Authentication token.
Here is the code for the second page:
private string BaseUri="https://login.windows.net/common/oauth2/token";
public string Redirecturi = "http://localhost:51642/CallBack.aspx";
public string ResourcesId = "https://api.office.com/discovery/";
private string ClienId = "180c6ac4-5829-468e-.....-822405804862"; ///truncated//azure
private string ClientSecert = "G4TAQzD8d7C4...OE6m366afv8XKbTCcyXr4=";//truncated
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString[OAuthConstants.AccessToken]))
{
// There is a token available already. It should be the token flow. Ignore it.
return;
}
if (!string.IsNullOrEmpty(Request.QueryString[OAuthConstants.Code]))
{
string _accessCode = Request.QueryString[OAuthConstants.Code];
HttpClient client = new HttpClient();
// BaseUri = Uri.EscapeDataString(BaseUri);
Redirecturi = Uri.EscapeDataString(Redirecturi);
ResourcesId = Uri.EscapeDataString(ResourcesId);
string url = string.Format("{0}?client_id={1}&redirect_uri={2}&grant_type=authorization_code&client_secret={3}&code={4}&grant_type=authorization_code&resource={5}", BaseUri, ClienId, Redirecturi, ClientSecert, _accessCode, ResourcesId);
var response = client.PostAsync(url, null);
var json = response.Result.Content.ReadAsStringAsync();
Response.Write(json);
}
}
But instead of Response I am get the following error. Which say include the grant_type in url. I have already added (you can check in code).
I get same error the same error without including it.
Here is the error
{"error":"invalid_request","error_description":"AADSTS90014: The request body must contain the following parameter: 'grant_type'.\r\nTrace ID: 2adb3a7f-ceb1-4978-97c4-3dc2d3cc3ad4\r\nCorrelation ID: 29fb11a0-c602-4891-9299-b0b538d75b5f\r\nTimestamp: 2015-07-15 09:58:42Z","error_codes":[90014],"timestamp":"2015-07-15 09:58:42Z","trace_id":"2adb3a7f-ceb1-4978-97c4-3dc2d3cc3ad4","correlation_id":"29fb11a0-c602-4891-9299-b0b538d75b5f","submit_url":null,"context":null}
Please help to know where or what is getting wrong.
Any kind of help will be appreciable
You're adding the parameters to the request querystring. You have to post the data in the request body.
var content = new StringContent(
"grant_type=authorization_code" +
"&client_id=" + ClienId +
"&redirect_uri=" + Redirecturi +
"&client_secret=" + ClientSecert +
"&code=" + _accessCode +
"&resource=" + ResourcesId,
Encoding.UTF8,
"application/x-www-form-urlencoded");
var response = httpClient.PostAsync(BaseUri, content);
var result = response.Result.Content.ReadAsStringAsync();
use FormUrlEncodedContent instead of StringContent (form data post)
var formContent = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "client_id", clientId },
{ "client_secret", clientSecret },
{ "code", authCode },
{ "redirect_uri", redirectUri },
{ "grant_type", "authorization_code" }
});
var response = await httpClient.PostAsync("https://login.microsoftonline.com/common/oauth2/token", formContent);
Sharing for future readers because this error is not specific to OneDrive only but can arise in other Microsoft tools
I was getting this error when working with Microsoft Bot Framework's Skype bot. In my case the bot file the appId and appSecret was wrongly set to clientId and clientSecret
Changing the same to appId and appSecret fixed the issue.

how to skip facebook app permissions dialog

Here, I am trying to authenticate user via login and after that I want to skip permissions dialog. But I am unable to achieve this, as it always asking for permissions for app to the user. My intention is if user is not logged into the facebook he/she should be prompted for facebook login and then I will fetch public information by using method Get("/me"). Let me know what I am doing wrong here.
public string GetFBAccessToken(string strAppID, string strAppSecret, string strUrl)
{
// Declaring facebook client type
var vFB = new FacebookClient();
string strAccessTok = string.Empty;
try
{
if (!string.IsNullOrEmpty(strAppID) && !string.IsNullOrEmpty(strAppSecret) && !string.IsNullOrEmpty(strUrl))
{
// Getting login url for facebook
var loginUrl = vFB.GetLoginUrl(new
{
client_id = strAppID,
client_secret = strAppSecret,
redirect_uri = strUrl,
response_type = "code",
state = "returnUrl",
//scope = "",
display = "popup"
});
// Redirecting the page to login url
if (HttpContext.Current.Request.QueryString["code"] == null)
{
HttpContext.Current.Response.Redirect(loginUrl.AbsoluteUri);
}
// Fetching the access token from query string
if (HttpContext.Current.Request.QueryString["code"] != null)
{
dynamic result = vFB.Post("oauth/access_token", new
{
client_id = strAppID,
client_secret = strAppSecret,
redirect_uri = strUrl,
code = HttpContext.Current.Request.QueryString["code"]
});
// Getting access token and storing in a variable
strAccessTok = result.access_token;
}
}
return strAccessTok;
}
catch (Exception ex)
{
//if (HttpContext.Current.Request.QueryString["response_type"] == "code")
//{
// var fb = new FacebookClient();
// var details = fb.Get("/me");
//}
return strAccessTok;
}
}
Regardless to the platform/ language you are using; solution can be as follows.
check use's logged in status. https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
based on Response status, forcefully call your action (i.e. Log in, Get Permission or any additional action if user is already connected). For Log in check this reference document from FB. https://developers.facebook.com/docs/facebook-login/login-flow-for-web/
No. You cannot skip the Login Dialog.
In fact, it is really important for an APP owner to build a trust relationship with your users. I would recommend you to follow the Login Best Practices while authenticating the users using your APP.

Facebook authentication response parameters are wrong -> infinite request loop

I an new to the facebook API and after some work I encountered a problem.
First, I am using the facebook SDK for communication with the facebook APIs.
In my app settings I chose that the response of the OAuth dialog should be query string instead of URI fragment.
On my server I got the following code:
void Page_Load()
{
string url = Request.Url.AbsoluteUri;
Facebook.FacebookOAuthResult result = null;
if (!Facebook.FacebookOAuthResult.TryParse(url, out result))
{
string redirectUrl = PivotServer.Helpers.GetFacebookOAuthUrl();
Response.Redirect(redirectUrl);
}
}
And thats my helper method:
public static string GetFacebookOAuthUrl()
{
FacebookOAuthClient oauth = new FacebookOAuthClient
{
AppId = "149637255147166",
AppSecret = "xxx",
RedirectUri = new Uri("http://mydomain.com/")
};
var param = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "display", "popup" }
};
Uri url = oauth.GetLoginUrl(param);
return url.AbsoluteUri;
}
I ran my page on a web server (IIS). When I open the page the first time I am asked to log in to facebook, which is alright, but then I ran into an infinity loop, because the Auth Token Parameter (from facebook) is an URI fragment instead if a query string (which I wanted (see picture above)).
The response URI looks like
http://mydomain.com/#access_token=AAACIGCNwLp4BAMccSoliF5EMGJm0NPldv5GpmBPIm9z7rRuSkiia7BM0uhEn1V88c8uOlWOfGc3C8sFC9tq90Ma0OwIm0tWLNU5BBAZDZD&expires_in=0&base_domain=mydomain.com
instead of
http://mydomain.com/?code=AAACIGCNwLp4BAMccSoliF5EMGJm0NPldv5GpmBPIm9z7rRuSkiia7BM0uhEn1V88c8uOlWOfGc3C8sFC9tq90Ma0OwIm0tWLNU5BBAZDZD&expires_in=0&base_domain=mydomain.com
Is that a bug from the OAuth API, or what am I doing very wrong here?
It's an issue with IE. Be sure to have a p3p header in each response from your server.
It has been too easy:
var param = new Dictionary<string, object>
{
{ "response_type", "code" }, // <--- "code" instead of "token"
{ "display", "popup" }
};

Adding Google Calendar entry without using setUserCredentials

I am following the example provided by Google for Market place app at
http://code.google.com/googleapps/marketplace/tutorial_dotnet.html
I got the google authentication working as in the example ,
My next task is to add a entry to Google calendar. I found following code for that, and it is also working fine
CalendarService service = new CalendarService(APPLICATION_NAME);
service.setUserCredentials(vUserName, vPassword);
Google.GData.Calendar.EventEntry entry = new Google.GData.Calendar.EventEntry();
// Set the title and content of the entry.
entry.Title.Text = title;
entry.Content.Content = contents;
// Set a location for the event.
Where eventLocation = new Where();
eventLocation.ValueString = location;
entry.Locations.Add(eventLocation);
When eventTime = new When(startTime, endTime);
entry.Times.Add(eventTime);
Uri postUri = new Uri("http://www.google.com/calendar/feeds/default/private/full");
// Send the request and receive the response:
AtomEntry insertedEntry = service.Insert(postUri, entry);
The problem i have is the following line, If i give my username and password it will work
service.setUserCredentials(vUserName, vPassword);
i have authenticated the user as in google example. So I don’t know the username and password of other users login to my site using their gmail.
How do i add a calender entry with the information i have?
I have seen several examples with RequestFactory authenticating the user. but couldn't find complete example that I can use
you will need to create a .pfx cert file and upload it to google and place it on your server.
create your AuthSubRequest URL
<asp:HyperLink ID="GotoAuthSubLink" runat="server"/>
GotoAuthSubLink.Text = "Login to your Google Account";
GotoAuthSubLink.NavigateUrl = AuthSubUtil.getRequestUrl("(return url)http://www.example.com/RetrieveToken", "https://www.google.com/calendar/feeds/", false, true);
after the person clicks on your auth link they are returned to your return url. get your session token as follows
String sessionToken = ""; //Save this for making your calls.
String certFile = "D:\\websites\\yourwebsite.com\\google.pfx";
String result = GetAuthSubSessionToken(Request["token"]);
protected AsymmetricAlgorithm GetRsaKey()
{
X509Certificate2 cert = new X509Certificate2(certFile, "");
RSACryptoServiceProvider privateKey = cert.PrivateKey as RSACryptoServiceProvider;
return privateKey;
}
public string GetAuthSubSessionToken(string singleUseToken)
{
string gatStr = "";
try
{
AsymmetricAlgorithm rsaKey = GetRsaKey();
try
{
sessionToken = AuthSubUtil.exchangeForSessionToken(singleUseToken, rsaKey).ToString();
gatStr = "Session Token = " + SessionToken;
}
catch (Exception e)
{
gatStr = "Error: I appears that the Google authentication server is experiencing an error. Try the authorizaton link again in a few minutes. <a href=\""
+ rtnUrl + "\" title=\"" + e.Message + "\">continue</a>";
}
}
catch (Exception E)
{
gatStr = "Error: rsa " + E.Message + E.StackTrace;
}
return gatStr;
}
save the session token and use CreateCalendarService in subsequent calls to create your calendar service.
public CalendarService CreateCalendarService()
{
GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cl", "YourName-calendarApp-1");
authFactory.Token = sessionToken;
authFactory.PrivateKey = GetRsaKey();
CalendarService cs = new CalendarService(authFactory.ApplicationName);
cs.RequestFactory = authFactory;
return cs;
}

Resources