Referring page to app - facebook-iframe

I have an application added to several fan pages.
Ideally, the application should work custom depending on the referring page.
How can I detect which page referred to the app.
Developing a Facebook Iframe app, Using PHP.
(Question posted on Facebook's dev forum as well:
http://forum.developers.facebook.net/viewtopic.php?id=108409)
Thx,
Oren.

As explained in the Page Tab Tutorial
When a user selects your Page Tab, you will received the signed_request parameter with one additional parameter, page. This parameter contains a JSON object with an id (the page id of the current page), admin (if the user is a admin of the page), and liked (if the user has liked the page). As with a Canvas Page, you will not receive all the user information accessible to your app in the signed_request until the user authorizes your app.

With the http referer, you will have the the Facebook proxy url.
In your case, I think you have to use the id of the page (passed in the signed request).

The following PHP snippet will output the signed_request received on the page tab. You will find the page ID needed in your case.
<?php
$appsecret = 'Your App Secret';
$signed_request = $_REQUEST['signed_request'];
$request = $_REQUEST;
$signed_request = parse_signed_request($signed_request, $appsecret);
print_r($signed_request);
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
?>

Using the new php-sdk, there is a quicker way to find out the referring page. $facebook->getSignedRequest() will return an array with the signed request, authorization token, page and user basic info.

Related

Django, Djoser social auth : State could not be found in server-side session data. status_code 400

I'm implementing an auth system with django and react. The two app run respectively on port 8000, 3000. I have implemented the authentication system using the Djoser package. This package uses some dependencies social_core and social_django. Everything seems to be configured ok. I click on login google button...I'm redirected to the google login page and then back to my front-end react app at port 3000 with the state and code parameters on the url.
At this point I'm posting those parameters to the backend. The backend trying to validate the state checking if the state key is present in the session storage using the code below from (social_core/backends/oauth.py)
def validate_state(self):
"""Validate state value. Raises exception on error, returns state
value if valid."""
if not self.STATE_PARAMETER and not self.REDIRECT_STATE:
return None
state = self.get_session_state()
request_state = self.get_request_state()
if not request_state:
raise AuthMissingParameter(self, 'state')
elif not state:
raise AuthStateMissing(self, 'state')
elif not constant_time_compare(request_state, state):
raise AuthStateForbidden(self)
else:
return state
At this point for some reasons the state session key is not there..and I receive an error saying that state cannot be found in session data ( error below )
{"error":["State could not be found in server-side session data."],"status_code":400}
I recap all the action I do:
Front-end request to backend to generate given the provider google-oauth2 a redirect url. With this action the url is generated also the state key is stored on session with a specific value ( google-oauth2_state ).
Front-end receive the url and redirect to google auth page.
Authentication with google and redirection back to the front-end with a state and code parameters on the url.
Front-end get the data form url and post data to back-end to verify that the state received is equal to the generated on the point (1).
For some reasons the state code is not persisted... Any ideas and help will be really appreciated.
Thanks to all.
ok so this is a common problem while you are working with social auth. I had the same problem for so many times.
The flow:
make a request to http://127.0.0.1:8000/auth/o/google-oauth2/?redirect_uri=http://localhost:3000/ (example)
you will get a authorization_url. if you notice in this authorization_url there is a state presented . this is the 'state of server side'.
now you need to click the authorization_url link.Then you will get the google auth page.After that you will be redirect to your redirect url with a state and a code. Remember this state should be the same state as the server side state .(2)
make post req to http://127.0.0.1:8000/auth/o/google-oauth2/?state=''&code=''.
if your states are not the same then you will get some issue.
everytime you wanna login , you need to make a request to http://127.0.0.1:8000/auth/o/google-oauth2/?redirect_uri=http://localhost:3000/
and then to http://127.0.0.1:8000/auth/o/google-oauth2/?state=''&code='' thus you will get the same state.
Without necessary detailed information, I can only tell 2 possible reasons:
You overrode backend with improper session operations(or the user was logged out before auth was finished).
Front-end used incorrect state parameter
You could test social login without front-end, let's say if you're trying to sign in with Google:
Enter the social login URL in browser, like domain.com:8000/login/google-oauth2/
Authorize
See if the page redirected to your default login page correctly
If yes, then probably you need to check your front-end code, and if no, then check your backend code.
At the end, if you're not so sensitive to the potential risk, you could also override GoogleOAuth2 class as following to disable state check:
from social_core.backends import google
class GoogleOAuth2(google.GoogleOAuth2):
STATE_PARAMETER = False
I think you may need some changes in you authorizing flow in step NO.3 and 4.
3.Authentication with google and redirection back to the front-end with a state and code parameters on the url.
4.Front-end get the data form url and post data to back-end to verify that the state received is equal to the generated on the point (1).
maybe you should redirect back to server side after google's authorization.
then at the server side, do the check! validate the state and code (maybe do more things).
then let server redirect to the front-end site you wanted to before.
for some reason, redirect to front-end directly will miss the param.. :-)
Finally, I reach a point where everything is working 200 percent fine, on local as well as production.
The issue was totally related to the cookies and sessions:
So rite answer typo is
make it look to your backend server as if the request is coming from localhost:8000, not localhost:3000,
means the backend domain should be the same always.
For making it possible you have two ways:
1: server should serve the build of the frontend then your frontend will always be on the same domain as the backend.
2: make a simple view in django and attach an empty template to it with only a script tag including logic to handle google auth. always when you click on signing with google move back you you're that view and handle the process and at the end when you get back your access token pass it to the frontend through params.
I used 2nd approach as this was appropriate for me.
what you need to do is just make a simple View and attach a template to it so on clicking on signIN with google that view get hit. and other process will be handled by the view and on your given URL access token will be moved.
View Code:
class GoogleCodeVerificationView(TemplateView):
permission_classes = []
template_name = 'social/google.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["redirect_uri"] = "{}://{}".format(
settings.SOCIAL_AUTH_PROTOCOL, settings.SOCIAL_AUTH_DOMAIN)
context['success_redirect_uri'] = "{}://{}".format(
settings.PASSWORD_RESET_PROTOCOL, settings.PASSWORD_RESET_DOMAIN)
return context
backend script code:
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script>
function redirectToClientSide(success_redirect_uri) {
window.location.replace(`${success_redirect_uri}/signin/`);
}
function getFormBoday(details) {
return Object.keys(details)
.map(
(key) =>
encodeURIComponent(key) + "=" + encodeURIComponent(details[key])
)
.join("&");
}
try {
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
const redirect_uri = "{{redirect_uri|safe}}";
const success_redirect_uri = "{{success_redirect_uri|safe}}";
if (params.flag === "google") {
axios
.get(
`/api/accounts/auth/o/google-oauth2/?redirect_uri=${redirect_uri}/api/accounts/google`
)
.then((res) => {
window.location.replace(res.data.authorization_url);
})
.catch((errors) => {
redirectToClientSide(success_redirect_uri);
});
} else if (params.state && params.code && !params.flag) {
const details = {
state: params.state,
code: params.code,
};
const formBody = getFormBoday(details);
// axios.defaults.withCredentials = true;
axios
.post(`/api/accounts/auth/o/google-oauth2/?${formBody}`)
.then((res) => {
const formBody = getFormBoday(res.data);
window.location.replace(
`${success_redirect_uri}/google/?${formBody}`
);
})
.catch((errors) => {
redirectToClientSide(success_redirect_uri);
});
} else {
redirectToClientSide(success_redirect_uri);
}
} catch {
redirectToClientSide(success_redirect_uri);
}
</script>
</body>

Login page customized depending on client

I would like to make the login page know which client requested the login in order to display some client-specific branding: Otherwise the user may be confused as to why he's redirected to this foreign login page on a different domain. A client logo will help reassure him that he's still on the right track.
What would be the most reasonable approach to get at that information?
EDIT: Note that by "client" I'm referring to the client web applications on whose behalf the authentication happens - not the user's browser. All clients are under my control and so I'm using only the implicit workflow.
To make this even more clear: I have client web apps A and B, plus the identity server I. When the user comes to I on behalf of B, the B logo should appear as we're no longer on B's domain and that may be confusing without at least showing a B-related branding.
Some Theory
The easiest way to get the ClientId from IdSrv 4 is through a service called IIdentityServerInteractionService which is used in the Account Controller to get the AuthorizationContext. And then follow that up with the IClientStore service that allows you to get the client details given the ClientId. After you get these details then its only a matter of sending that info to the view for layout. The client model in IdSrv 4 has a LogoUri property that you can utilize to show an image at login per client.
Simple Example
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Login(string returnUrl = null)
{
var context = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (context?.IdP != null)
// if IdP is passed, then bypass showing the login screen
return ExternalLogin(context.IdP, returnUrl);
if(context != null)
{
var currentClient = await _clientStore.FindClientByIdAsync(context.ClientId);
if (currentClient != null)
{
ViewData["ClientName"] = currentClient.ClientName;
ViewData["LogoUri"] = currentClient.LogoUri;
}
}
ViewData["ReturnUrl"] = returnUrl;
return View();
}

force.com sites - direct link to salesforce visual force page not working

Am facing an obstacle using force.com site
a template email is used to send to portal users with direct link to some record in salesforce
example https://example.force.com/SamplePage?id=xxxxx
by trying to use refURL param half way was done as in the next example :
https://example.force.com?refURL=/SamplePage?id=xxxxx
but passing from an obstacle to facing another,now every time i click on the new link in the email i have to re-login again regardless that i just made a login.
so for the first attempt its logical to input the credentials to login to the site but i need to prevent when the session still on to re login again every time by clicking on the link from my email
my login code in Apex is as below :
global PageReference login() {
//Get refUrl
String strRefUrl = System.currentPageReference().getParameters().get('refURL');
//Get startUrl
String strStartUrl = System.currentPageReference().getParameters().get('startURL');
if(strRefUrl != null && strRefUrl != '' && ! strRefUrl.startsWithIgnoreCase(Site.getBaseInsecureUrl() )){
//Need to remove domain part because site.login() does not redirect to absolute URL
strStartUrl = strRefUrl.replace(Site.getBaseRequestUrl(),'');
}
else if (strRefUrl.startsWithIgnoreCase(Site.getBaseInsecureUrl())){
//Redirect to base URL if refUrl is empty
strStartUrl = Site.getBaseUrl() + '/LoginPage';
}
return Site.login(username, password, strStartUrl );
}

PrestaShop - Login programmatically

I am writing a android and windows native app. The native app stores the login details as reated for mulitple other web apps, and logs them into this when browsing to them from the native app.
one of the buttons in my app open a prestashop site for a authenticated user. How can i set the username and password and log that user in to the site programmitcally, giving the illusion and user experience that he has been seemlessly authenticated and accessed to his shop.
I know this is an old question, but theres another way which i find better for the purpose.
You include the AuthController from the controllers folder, set your post-parameters and execute the postProcess() method. After this, you can check the "$authController->errors" array for errors. If it's empty - the login was successful.
Example:
public function hookDisplayHeader()
{
if ($this->context->cookie->isLogged())
{
return;
} else {
$acceptLogin = false;
if( isset( $_POST["email"] ) && isset( $_POST["passwd"] ) )
{
$acceptLogin = $this->attemptLogin($_POST["email"],$_POST["passwd"]);
}
if( $acceptLogin )
return;
die( $this->display(__FILE__, 'logintemplate.tpl') );
}
}
protected function attemptLogin($email, $password)
{
include _PS_FRONT_CONTROLLER_DIR_ . "AuthController.php";
$auth = new AuthController();
$auth->isAjax = true;
$_POST["email"] = $email;
$_POST["passwd"] = $password;
$_POST["SubmitLogin"] = true;
$auth->postProcess();
if( count($auth->errors) > 0 )
{
$this->context->smarty->assign( "errors", $auth->errors );
return false;
} else {
return true;
}
}
Edit: This no longer works with Prestashop 1.6. As of PS 1.6 $auth->postProcess() either redirects or sends the ajaxs response immediately. There is no way to circumvent this. If you want to do something after login, you have to make two ajax calls.
Basically do the same as the PrestaShop login form does, which is (for v1.5 at least):
Sending a POST request to http(s)://yourshop.com/index.php?controller=authentication with the following parameters:
email: your customer's email address
passwd: your customer's password
back: name of the controller you want to be redirected to after success (ex: my-account)
SubmitLogin: put anything there, it just needs to be true, so that the controller knows it's a login action
If it doesn't work, your version may work differently and you will have to check the network tab of your favourite developer tool, to see what kind of request is sent with which parameters.

Google Custom Search and Passing along Querystring Variables

I am working on a web app project that has been in development for long time. The app has two sides, the majority of the site is publicly accessible. However, there are sections that require the user to be logged in before they can access certain content.
When the user logs in they get a sessionid (GUID) which is stored in a table in the database which tracks all sort for data about the user and their activity.
Every page of the app was written to look if this session id variable exists or not in the querystring. If a user tries to access one of these protected areas, the app checks to see if this sessiond variable is in the querystring. If i is not, they are redirected to the login screen.
The flow of the site moves has the user moving seamlessly from secured areas to non-secured areas, back and forth, etc.
So we did a test run with the Google Custom Search and it does an awesome job picking up all our dynamic content in these public areas. However, we have not been able to figure out how to pass the sessionid along with the search results IF the user is logged in already.
Is it possible to pas querystring variables that already exist in the url along with the search results?
As far as I know, this is not possible. Google doesn't give you the possibilty to modify the URL's of the Search Results in their Custom Search.
A possible solution would be to store your Session-Key to a Cookie, rather than passing it with every URL.
Use the parseQueryFromUrl function
function parseQueryFromUrl () {
var queryParamName = "q";
var search = window.location.search.substr(1);
var parts = search.split('&');
for (var i = 0; i < parts.length; i++) {
var keyvaluepair = parts[i].split('=');
if (decodeURIComponent(keyvaluepair[0]) == queryParamName) {
return decodeURIComponent(keyvaluepair[1].replace(/\+/g, ' '));
}
}
return '';
}
Select RESULTS ONLY option in the Look & Feel and it will provide you with the code.
www.google.com/cse/

Resources