How to encode the redirect_uri for facebook login - c#

I'm trying to build a login link for facebook and I'm I'm getting errors only in some cases. I'm trying to specify a a querystring parameter in redirect_uri token so that I can redirect them back to a specific area of my site after logging in. Here's what works and what doesn't work.
&redirect_uri=http://mydomain.com/login?returnUrl=returnUrl - works
&redirect_uri=http://mydomain.com/login?returnurl=/return/url -doesn't work
&redirect_uri=http%3a%2f%2fmyagentcheckin.com%2flogin%3freturnUrl%3d%2freturn%2furl -doesn't work
It seems that the / in the querystring are causing it to fail. Facebook returns an error when I try it. Anyone know of a way around this?

Instead of including the returnUrl parameter as part of your redirect_uri value, use the state parameter to store this data.
For instance,
https://graph.facebook.com/oauth/authorize?type=web_server&client_id={appid}&redirect_uri=http://www.yoursite.com/oauth/handshake&state=/requested/page

I have experienced something similar, especially with multiple redirects as above.
My solution is to put the returnUrl into the user's session (or perhaps a cookie), so I don't have to wrestle with double-encoding. For the redirect_url, just omit the querystring.

Try using this API that put together. It will remove the hassle of this for you.
No url encoding necessary.
Sample Authentication
Imports Branches.FBAPI
...
Dim SI As New SessionInfo("[application_id]","applicaiton_secret")
SI.AuthenticateUser("http://[my url]", New SessionInfo.PermissionsEnum(){SessionInfo.PermissionsEnum.email, SessionInfo.PermissionsEnum.read_stream}))
Read the response from the URL you provided above from that page.
Dim FSR = FS.ReadFacebooAuthResponse

When I tried what you do, I got a redirect callback something like this.
http://mydomain.com/login?returnurl=%2Freturn%2Furl&code=...
And I decode the "returnurl" value.
Then it worked fine for me.

Related

Updating the displayed URL in the browser using .NET Core

So, I have a certain webpage (view) that I have created. I have a requirement where I need to update the displayed URL in the browser's to show a different path to this page and update the querystring.
Update: I don't want to actually redirect the page, this is merely a cosmetic update. To make the URL appear differently that what it was. It's a requirement our customer support team wanted. :p
Ex.
https://www.myserver.com/error/
I need to update the path in the URL depending on the type of error, like so:
https://www.myserver.com/#/order-completed?var=someguid
My error page handles various situations you see.
I know this is easily done in JS, but I want to be able to do this from my error page Controller.
Could someone lend a hand? I'd super appreciate it!
I think "update the path" means you simply have to redirect the browser to that url. If you are using ASP.NET MVC, you can use the Redirect controller method like this:
return Redirect("https://www.myserver.com/#/order-completed?var=someguid");
So, I went the way of JS afterall. I call it from window.onload in the View.
var fromController = '#ViewData["NewURL"]';
histoy.pushState(null, '', fromController);
In the Controller, in the Index() action
ViewData["NewURL"] = #"/myURL/myview?user=2342434";
return View();

Query String Parameter Being Lost on Request

i'm developing an MVC 4 web application.
I'm trying to make an url that changes in an authorized/unauthorized context.
I'm generating the following url for unauthorized user:
http://localhost/vendas-web/Login?ReturnUrl=%2Fvendas-web%2FClienteNovo%2FIndex%299999
The first time I've tested, it worked just fine.
But.. the second time I've tried, the query string got lost.. and the url turned into:
http://localhost/vendas-web/Login
When i test it against chrome on anonymous tab, it works FINE.
When i change the value of the last parameter, it works FINE.
There's some sort of cache related to this ?
What i'm doing wrong ?
Soo, my question is:
How do i keep my full url in any scenario ??
Ty
There's really not enough information here, but what you're likely talking about is that the first time a user needs to be authorized, they are automatically redirected to the first URL, which includes the ReturnUrl bit. That's built into the framework to allow the user to be redirected back to that URL after logging in. However, if you need to persist this past that initial first redirect to the login page, that's on you. Any links must manually add the query string param:
#Url.Action("SomeAction", new { ReturnUrl = Request["ReturnUrl"] })
And any forms must include it as a hidden input:
#Html.Hidden("ReturnUrl", Request["ReturnUrl"])
Otherwise, yes, it will be lost, because the literal URL you're now requesting doesn't include it. It's not just magically appended.
My problem was cache...
I've used this annotation to avoid using cache by application.
[OutputCache(NoStore = true, Duration = 0)]

login to ajax web page from c# code

i'm trying to log in a site with username + password through a c# code.
i found out that it uses Ajax to authenticate...
how should i implement such login ?
the elements in the web page doesn't seem to have an "id"...
i tried to implement it using HtmlAgilityPack but i don't think this is the correct direction...
i can't simulate a click button since i don't find "id" for the button.
if (tableNode.Attributes["class"].Value == "loginTable")
{
var userInputNode =
tableNode.SelectSingleNode("//input[#data-logon-popup-form-user-name-input='true']");
var passwordInputNode =
tableNode.SelectSingleNode("//input[#data-logon-popup-form-password-input='true']");
userInputNode.SetAttributeValue("value", "myemail#gmail.com");
passwordInputNode.SetAttributeValue("value", "mypassword");
var loginButton = tableNode.SelectSingleNode("//div[#data-logon-popup-form-submit-btn='true']");
}
This question is quite broad but I'll help you in the general direction:
Use Chrome DevTools (F12) => Network tab => Check the "Preserve Log". An alternative could be Fiddler2
Login manually and look at the request the AJAX sends. Save the endpoint (the URL) and save the Body of the request (the Json data that's in the request with username and password)
Do the post directly in your C# code and forget about HtmlAgilityPack unless you need to actually get some dynamic data from the page, but that's rarely the case
Login with something like this code snippet: POSTing JSON to URL via WebClient in C#
Now you're logged in. You usually receive some data from the server when you're logging in, so save it and use it for whatever you want to do next. I'm guessing it might have some SessionId or some authentication token that your future requests will need as a parameter to prove that you're actually logged in.

Redirect in MVC does not work as expected

I have the following code:
var redirectIp = string.Format("{0}{1}", Session["CurrentHost"], ip.PathAndQuery);
return new RedirectResult(redirectIp);
When I check the value of redirectIP it gives me:
redirectIp "127.0.0.1:84/Administration/Accounts/ShowSummary?ds=0001" string
However when I step through the code the browser opens and gives me the following:
http://127.0.0.1:84/Administration/Accounts/127.0.0.1:84/Administration/Accounts/ShowSummary?ds=0001
I am totally confused. Anyone have any idea what's happening?
That is how urls, http and browsers work. You forgot the protocol part, so the redirect actually does work as expected, given the url that you are redirecting to.
var redirectIp = string.Format("http://{0}{1}", Session["CurrentHost"], ip.PathAndQuery);
return new RedirectResult(redirectIp);
This will work better for now, but to be able to also cover https, you're better off storing the protocol part in a session variable along with the hostname.

Problem getting access_token after migrating to OAuth 2.0

I have tried migrating my app to the OAuth 2.0 routine. I am having trouble getting the access_token from the cookie set by the JavaScript API. I decode the information in the cookie, but instead of an access_token and the user information I get a code. This seems like a rather weird change.
Is there any workaround for this, because it seems that you can't get your code exchanged to an access_token when you haven't specified a redirect_uri when you acquired the code.
I have considered just taking the access_token from the response in the JavaScript API and storing it in a cookie, but that kinda defeats the whole purpose of the extended security and I wanted to ask if there was a proper way to do it.
Could be that I am doing something wrong though, and if that is the case please tell me :)
EDIT
I am aware that the cookie holds a signed request, but according to the docs that signed request should hold the information I require like access_token and uid, but in my instance it only holds the code. That is basically the part I don't understand.
Turns out that (even though it is not documented) we need to exchange the code for an access_token ourselves. I think this is a total waste since that was the nice thing about the old cookie. It was fast and easy to get the access_token.
Anyway. To get the access_token from the new cookie you need to do the following:
public string ReturnAccessToken()
{
HttpCookie cookie = htc.Request.Cookies[string.Format("fbsr_{0}", facebookAppID)];
string jsoncode = System.Text.ASCIIEncoding.ASCII.GetString(FromBase64ForUrlString(cookie.Value.Split(new char[] { '.' })[1]));
JsonData data = JsonMapper.ToObject(jsoncode);
getAccessToken(data["code"].ToJson()
}
private string getAccessToken(string code)
{
//Notice the empty redirect_uri! And the replace on the code we get from the cookie.
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}", "YOUR_APP_ID", "", "YOUR_APP_SECRET", code.Replace("\"", ""));
System.Net.HttpWebRequest request = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
System.Net.HttpWebResponse response = null;
using (response = request.GetResponse() as System.Net.HttpWebResponse)
{
System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
string retVal = reader.ReadToEnd();
return retVal;
}
}
public byte[] FromBase64ForUrlString(string base64ForUrlInput)
{
int padChars = (base64ForUrlInput.Length % 4) == 0 ? 0 : (4 - (base64ForUrlInput.Length % 4));
StringBuilder result = new StringBuilder(base64ForUrlInput, base64ForUrlInput.Length + padChars);
result.Append(String.Empty.PadRight(padChars, '='));
result.Replace('-', '+');
result.Replace('_', '/');
return Convert.FromBase64String(result.ToString());
}
This may seem a bit redundant, but I suppose you can store the access_token in a session variable. If you do this and iFrame the your app on Facebook you need to know that it will not work in IE 6, 7 and 8 if the user have set his browser privacy settings to medium. There is a workaround for this, but as it is not a part of this question I will not write it. If people really want it, write a comment and I will show it :)
-----------------------------------EDIT------------------------------------------
When using any of the old IE browsers you can't use cookies or session variables in pages that are Iframed in, like your pages on Facebook. This is a problem that can't really be solved sufficiently in coding. By sufficiently I mean that the solution is not nice. You need to set the p3p-header in your response. You can of course do this in coding for all the pages that you service, but the easiest solution (if you are using a .NET server to host your pages) is to set up a p3p policy for the IIS. A guide for this can be seen in http://support.microsoft.com/kb/324013. It shouldn't matter what you write in the p3p policy (if you check Facebooks own you can see that they use "We don't have a p3p policy), the important part is that there stands something. I have had troubles just using random text though, but if you use the text in the example there shouldn't be a problem :)
This took me forever to find out, so I hope someone can use it :D
Unfortunately I don't have the answer directly, but I do have a documentation bug that I filed against facebook in order to try to get the documentation there: http://bugs.developers.facebook.net/show_bug.cgi?id=20363
I have a similar problem that when I try to decode the signedRequest from the authResponse of FB.login, they payload contains something like:
{"algorithm":"HMAC-SHA256","code":"THE_CODE_HERE","issued_at":1315433244,"user_id":"THE_USER_ID"}
As you stated, the docs do talk about how to turn that code into an access_token. That appears to be in the "Server Side" documentation here: http://developers.facebook.com/docs/authentication/
If you grab the accessToken from FB.login you can get it from the js and cache it, but as you said, that isn't actually signed, and could relatively easily be faked.
And you're right, this doesn't appear to have any of the useful information that's described here: developers.facebook.com/docs/authentication/signed_request/ (http removed since I don't have enough reputation points yet to post more than 2 links - sorry)
Perhaps you can vote up my bug? I'll post this link on that bug too.
fbsr_APP_ID cookie is actually a signed_request, check out facebook official docs how do you decode signed request verify signature and get the user information. You can look also at official php SDK source how they get access token from there.
You have to use the code to get the actual access_token.

Categories