How to login with Facebook javascript SDK in hybrid HTML5 based application - ios

I'm building an hybrid app for Android and iPhone based on html5. I want to implement in my app login with Facebook. All the Html on the application are a local on the device; I don't have a server so I want to save the token from Facebook in the local storage. Is it possible to implement this with Facebook javascript SDK?
I tried the code from Facebook developer site:
<html>
<head></head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '{your-app-id}',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
testAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
FB.login();
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login();
}
});
};
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
</script>
<!--
Below we include the Login Button social plugin. This button uses the JavaScript SDK to
present a graphical Login button that triggers the FB.login() function when clicked. -->
<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
</body>
</html>
But I get the following error in browser console:
"Given URL is not allowed by the Application configuration.: One or
more of the given URLs is not allowed by the App's settings. It must
match the Website URL or Canvas URL, or the domain must be a subdomain
of one of the App's domains. "

In your apps config.xml you should have something like <access origin="*">

Related

Unable to log in Dailymotion user using JS SDK

I have a React app from which I want to upload videos to the account of the logged in user. I have successfully done this retrieving tokens manually and calling the API but can't find a way to log in using the JS SDK in my React app.
I present the user with a button for log in:
e.preventDefault()
window.DM.login(
function (response) {
if (response.session) {
// user successfully logged in
console.log(response)
} else {
// user cancelled login
console.log(response)
}
},
{
client_id: my_id,
scope: "read write",
response_type: "code"
}
)
}
The login popup appears, I log in and get sent to the callback url. However, refreshing the original site, or the callback popup, still shows as no session and without login. I check with:
status === 'ready' &&
window.DM.getLoginStatus(function (response) {
if (response.session) {
// logged in and connected user, someone you know
console.log(response)
} else {
// no user session available, someone you dont know
console.log(response)
}
})
})
and I always get { status: "unknown", session: null }
Loading the SDK is handled with a hook const status = useScript('https://api.dmcdn.net/all.js')
Do I need to handle something manually from the callback page? Isn't the SDK supposed to handle it in the background? I would appreciate some insights on what I might be doing wrong.
Thanks.
As always, I spent hours trying to find a solution and, as soon as I post, I find it:
Client_id and response_type must not be passed in DM.login.
Instead, you have to pass the API key in DM.Init, like so:
useEffect(() => {
status === 'ready' &&
window.DM.init({
apiKey: '123456789',
status: true, // check login status
cookie: true // enable cookies to allow the server to access the session
});
})
This brings up the popup and after inputting the credentials the SDK correctly detects the session, closing the popup and authing the user.

How to detect that the current request is an authentication callback?

I have a single-page JavaScript application and I'm using the Auth0 service for signup/login.
I have integrated the Lock widget and I'm saving a string to localStorage after a user is authenticated, like so:
lock.on("authenticated", function(authResult)
{
localStorage.setItem('login', authResult.idToken);
}
The problem is that when Auth0 redirects them back to my application after logging in, the authenticated event is fired only after page loaded, but by that time, I've already done the check to see if the localStorage string is set (which it is not); therefore, the user just keeps getting asked to login again:
if(localStorage.getItem('login') == undefined)
{
lock.show(function(err, profile, token)
{
// ...
}
}
I tried to see if there was anything special passed in to the page after a callback - but the referrer isn't always there.
If I don't automatically prompt the user to login, but instead show a login button - the authenticated event never fires for some reason.
How do I get around this?
Based on the information provided you seem to be using Lock in redirect mode and if that's the case you can use the hash_parsed event as a way to know if Lock found a response that it will process.
Every time a new Auth0Lock object is initialized in redirect mode (the default), it will attempt to parse the hash part of the URL, looking for the result of a login attempt. After that, this event will be emitted with null if it couldn't find anything in the hash. It will be emitted with the same argument as the authenticated event after a successful login or with the same argument as authorization_error if something went wrong.
Leveraging this event you could do the following:
Subscribe to the hash_parsed event:
If hash_parsed is emitted with null and localStorage has no indication the user already logged in then redirect to login.
If hash_parsed is emitted with a non-null value that either the authenticated or authorization_error will be emitted and you can react accordingly.
Some sample code:
lock.on("hash_parsed", function (response) {
if (!response && !localStorage.getItem('login')) {
// Redirect to the login screen
} else {
// Either the user is already logged in or an authentication
// response will be processed by Lock so don't trigger
// an automatic redirect to login screen
}
});

Unable to Logout of Facebook within Unity IOS [duplicate]

I've managed to successfully log in FB using FB.Login function. Now I want to log out:
FB.Logout();
Debug.Log("FB IS LOGGED IN " + FB.IsLoggedIn);
I am expecting the above code to print the value of FB.IsLoggedIn as false and to ask me for a login and password on the next FB.Login.
In fact the value of FB.IsLoggedIn is true and I am not being logged out: next call to FB.Login does not ask for password and I am not being logged out when I open facebook site in my browser.
I've also tried to use the undocumented request to https://www.facebook.com/logout.php?next=[YourAppURL]&access_token=[ValidAccessToken] but it didn't make any effect for me.
How can I log the user out of facebook in my standalone unity application?
In fact what I need is to log in with different login and password.
Maybe I can invalidate the access token somehow which will cause the FB to ask me for login and password again?
Any help is much appreciated.
SDK version: 5.0.1
Build version: 140401.725cc2ecbc9002a
Unity Version 4.3.3f1 (c8ca9b6b9936)
I believe the FB.Logout operation is asynchronous, and the value of FB.IsLoggedIn would be true immediately after calling FB.Logout(). If you look at the documentation, it says:
You almost certainly should not use this function, which is provided
primarily for completeness. Having a logout control inside a game that
executes a Facebook-wide logout will violate users' expectations.
Instead, allow users to control their logged-in status on Facebook
itself.
Actually FB.Logout() has no delegate to let you know that account is successfully logout, so you have to create your own listner.
Secondly it will not sign you out from the actual device Facebook app or browser.
If you want to sign in with different account, so you can do by signing out explicitly from the app or browser.
Here is the code for how to detect that if you are logged out. It may useful to show Login and Logout button for Facebook that when to Login or Logout.
Here is the code from that you can determine the user has logged out within the Game.
public void OnFacebookLogout()
{
if (FB.IsLoggedIn)
{
FB.Logout ();
StartCoroutine ("CheckForSuccussfulLogout");
}
}
IEnumerator CheckForSuccussfulLogout()
{
if (FB.IsLoggedIn)
{
yield return new WaitForSeconds (0.1f);
StartCoroutine ("CheckForSuccussfulLogout");
} else
{
// Here you have successfully logged out.
// Do whatever you want as I do, I just enabled Login Button and Disabled
// logout button through this method.
EnableFacebookLoginButton ();
}
}
I'm not sure if it is correct but why not just do some while loop?
IEnumerator FBLogout (){
FB.Logout ();
while (FB.IsLoggedIn){
print ("Logging Out");
yield return null;
}
print ("Logout Successful");
}

Need to Authorize app everytime - hybridauth laravel localhost

i have integrated hybridauth with laravel and able to login to my app with twitter using hybridauth. when i first time login to my app with twitter, i have authorized my app. so, generally after next time i don't need to authorize my app for login cause i have accept the authorization first time.
but it is not happening. my app is force to authorize by twitter every time i try to login twitter.
i am trying this on localhost. should i need to check it in a live server?
i am using this code, all Credential are setted:
Route::get('social/{action?}', array("as" => "hybridauth", function($action = "")
{
// check URL segment
if ($action == "auth") {
// process authentication
try {
Hybrid_Endpoint::process();
}
catch (Exception $e) {
// redirect back to http://URL/social/
return Redirect::route('hybridauth');
}
return;
}
try {
// create a HybridAuth object
$socialAuth = new Hybrid_Auth(app_path() . '/config/hybridauth.php');
// authenticate with Google
$provider = $socialAuth->authenticate("Twitter");
// fetch user profile
$userProfile = $provider->getUserProfile();
}
catch(Exception $e) {
// exception codes can be found on HybBridAuth's web site
return $e->getMessage();
}
// access user profile data
echo "Connected with: <b>{$provider->id}</b><br />";
echo "As: <b>{$userProfile->displayName}</b><br />";
echo "<pre>" . print_r( $userProfile, true ) . "</pre><br />";
// logout
$provider->logout();
}));
I have found the solution. it was not in the code to fix something. It was the settings of the twitter app. To avoid this kind of problem, you should select Read and Write option rather than Read, Write and Access direct messages option from the Permission section of your app's settings.
If you select Read, Write and Access direct messages, then twitter will always prompt you to authorize your app whenever you try to login in your app via your twitter app. See the Image bellow for more clear information.
Hope it will help you. Thanks

Application Error when logging in with JavaScript SDK, using oauth opt in login

Here is my code:
FB.init({
appId : this.api_id,
status : true,
cookie : true,
xfbml : true,
oauth : true,
channelUrl : 'https://blah.com/facebook/channel' // custom channel
});
FB.login(function(response) {
if (response.authResponse) {
if (response.perms) {
// user is logged in and granted some permissions.
if(typeof redirect === 'function') {
redirect();
}else {
window.location = redirect;
}
} else {
// user is logged in, but did not grant any permissions
}
} else {
// user is not logged in
}
},{
scope: 'email'
}
);
So what happens is that if i have oauth no set in FB.init everything works fine but if i add in
oauth is true then i will get back
<span>Application Error: There was a problem getting data for the application you requested. The application may not be valid, or there may be a temporary glitch. Please try again later. </span>
from the request to /dialog/oauth
I followed all the roadmap to oauth 2 here https://developers.facebook.com/blog/post/525/
and still no luck, something seems a bit off here.
And no all the code posted in not all the code i have, before FB.login gets called i make sure
FB.init has already been called. Any help greatly appreciated
Check if your application is in sandbox mode. If it is, switch sandbox mode off and try again.
If sandbox mode is on FB will not recognize your app and a call to Facebook.init will fail silently, when you are not logged in, returning the response 'Application Error: There was a problem getting data for the application you requested. The application may not be valid, or there may be a temporary glitch. Please try again later.'

Resources