Getting Facebook callback error even after enabling 'Embedded browser OAuth Login' and specifying the callback url - ruby-on-rails-4

I have a rails(4.2.0) application that uses Facebook login functionality. The main gems are devise(3.4.0) and omniauth-facebook(2.0.0). I have registered the application on Facebook and have been using its test app for development. The Facebook login functionality works in the development env.
When trying to use the facebook login feature on the production server, I get error as "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."
The details for settings for test app being used in the dev env are as -
Settings:
Basic:
App Domains: 'localhost'
Website:
Site URL: 'http://localhost:3000'
Advanced:
OAuth Settings:
Embedded browser OAuth Login: Yes
Valid OAuth redirect URIs: "http://localhost:3000/users/auth/facebook/callback"
The details for settings for registered app being used in the production env are as -
Settings:
Basic:
App Domains: 'www.mysite.co'
Website:
Site URL: 'http://www.mysite.co'
Advanced:
OAuth Settings:
Embedded browser OAuth Login: Yes
Valid OAuth redirect URIs: "http://www.mysite.co/users/auth/facebook/callback"
I have specified the following in my secrets.yml
development:
secret_key_base: some_secret_key
facebook:
app_id: test_app_id
app_secret: test_app_secret
production:
secret_key_base: some_secret_key
facebook:
app_id: registered_app_id
app_secret: registered_app_secret
And have been using the creds from secrets.yml in the devise initialiser as
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
require 'omniauth-facebook'
config.omniauth :facebook, Rails.application.secrets.facebook['app_id'], Rails.application.secrets.facebook['app_secret'], scope: ['user_photos', 'email', 'public_profile']
The actual domain name(blackened) has no typos anywhere and is same wherever it is used.
Contains of routes.rb related to omniauth are as
cat config/routes.rb
Rails.application.routes.draw do
root 'home#index'
devise_for :users, controllers: { omniauth_callbacks: "users/omniauth_callbacks" }
# routes related to other controllers
end
The routes are as below
bundle exec rake routes | grep user
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
user_omniauth_authorize GET|POST /users/auth/:provider(.:format) users/omniauth_callbacks#passthru {:provider=>/facebook/}
user_omniauth_callback GET|POST /users/auth/:action/callback(.:format) users/omniauth_callbacks#:action
The only code related to omniauth in the entire app is as
$ cat app/controllers/users/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
#You need to implement the method below in your model (e.g. app/models/user.rb)
#user = User.from_omniauth(request.env["omniauth.auth"])
if #user.persisted?
sign_in_and_redirect #user, event: :authentication #this will throw if #user is not activated
set_flash_message(:notice, :success, kind: "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
end

Upon further digging the problem, it was observed that the error didnt occur when 'www.example.com' was specified in the url and hence, the callback worked. When 'example.com' was specified in the address bar and facebook login tried, the login crashed with the above error.
So, I fixed the above issue by making some changes to the settings in for the facebook app. I donno if this is the right approach but it worked out. Just making the change as in point 2 didnt solve the problem.
Changes are:
1) Specified the 'App Domains' with 'example.com' and 'www.example.com'
2) Enabled 'Client OAuth Login' to 'Yes'
3) Specified 'Valid OAuth redirect URIs' with 'http://example.com/users/auth/facebook/callback' and 'http://www.example.com/users/auth/facebook/callback'

Ok, so I assume that you have a web app NOT running on Facebook that simply uses the Facebook OAuth flow for login functionality, correct? If so, you must enable "Client OAuth Login" in your application settings for the production environment. If you don't, then the web OAuth flow will not work. See this article: https://developers.facebook.com/docs/facebook-login/security

Related

Django all auth facebook login with Use Strict Mode for Redirect URIs

Hi I am trying to implement Facebook login for my website using Django Allauth.
As we can no longer disable Use Strict Mode for Redirect URIs I am getting an error when I try to login via facebook.
The callback URL formed at the time of Facebook login is of this format -
https://example.com/accounts/facebook/login/callback/?code=AQB7W48oY-1XxZv2xU9iahxS80ZPs4oBNLlXWTY7Y93dclyIElEPG-jWKB5ELV7Pv11ckcRYg3L67Wfcz6xqC8yhNLBaFaOQjd4F2AEp8nfScltnY3LoY79g9NjtslCSbQnSlc_hDdBm_rxQtScz-rLChNvAJaky3KYMG_USSTkm9qdyvw5lIMdcIHQjz3CTF8KdgmuFG1T8_WvVqdGDEpfhC_PD7w5tnkcChBEowHnWR656DYa1wrMR1fbP2rqxBocNn6fKPCy_GM_DZynPp8mx0F0YP55vzw2Kv8KchB2nxCaHwQ4dRvJq785w5CfCgDVc6REhbc3CNG2KqZxdxjuG&state=eukVyjHYk04X#_=_
This URL contains the query params code and state because of which it is not an exact match and I checked it via Redirect URI to Check which reported it as invalid.
So on the authentication_error.html I get the following error.
{'provider': 'facebook', 'code': 'unknown', 'exception':
OAuth2Error('Error retrieving access token:
b'{"error":{"message":"Can\'t load URL: The domain of this URL
isn\'t included in the app\'s domains. To be able to load this
URL, add all domains and sub-domains of your app to the App Domains
field in your app
settings.","type":"OAuthException","code":191,"fbtrace_id":"AxoTkIBeoUSKsxuWvMx-Wg4"}}'',)}
My Valid OAuth Redirect URIs has the following URL's
https://example.com/accounts/facebook/login/callback/
https://www.example.com/accounts/facebook/login/callback/
Please help me with this issue, I have looked into all the existing issue but haven't found a solution.
For anyone facing a similar issue, it could be because you missed to add this line to your settings.py file.
ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'

JWT authentication between Django and Vue.js

I wish to create a public area on a website containing standard Django and templates. When a user logs in to the members area, they are logged in to a SPA (using Vue.js) and Django Rest Framework. I will be using JWT's to handle authentication between the SPA and backend once the user has logged in to the members area.
This is the user journey:
User browses around the public areas of the site (served by normal Django and templates).
User decides to signup / login to the members area.
Django Rest Framework generates a JWT for the user and returns the token along with the index.html of the SPA
The user continues to use the SPA with the JWT
Is the above possible and how would it be done? More specifically, the issue is that the user is not logging in to the SPA and requesting a JWT. They are logging in to regular Django and getting returned a JWT along with the SPA. That JWT would then be used from that point onwards.
This is something that I've used with laravel, but the principle should be the same.
I've placed vue-cli generated code into the subfolder frontend.
This is trimmed content of the file vue.config.js, which you need to add manually to the vue-cli project root.
const path = require('path')
/*
vue-cli is initialized in project subfolder `frontend`
and I run `npm run build` in that sub folder
*/
module.exports = {
outputDir: path.resolve(__dirname, '../public/'),
/*
https://cli.vuejs.org/config/#outputdir
!!! WARNING !!! target directory content will be removed before building
where js, css and the rest will be placed
*/
assetsDir: 'assets/',
/*
Where `public/index.html` should be written
- this is example for the laravel, but you can change as needed
- .blade.php is laravel template that's served trough laravel.
So you could inject JWT into `index.html`
- Check https://cli.vuejs.org/guide/html-and-static-assets.html
for the syntax before adding values
*/
indexPath: path.resolve(__dirname, '../resources/views/index.blade.php'),
devServer: {
host: '0.0.0.0',
port: 8021,
proxy: {
/*
Proxy calls from
localhost:8021/api (frontend)
localhost:8020/api (backend)
*/
'/api': {
target: 'http://localhost:8020',
changeOrigin: true,
}
}
}
};

Dropbox and Django SSO using SAML

Summary
I am looking to use Dropbox SSO functionality by using the authentication from a Django site. Note that I'm not looking to use SAML as a backend for my Django site.
Resources
1) Dropbox Custom SSO help page: https://www.dropbox.com/en/help/1921#custom
2) Creating a SAML response: https://robinelvin.wordpress.com/2009/09/04/saml-with-django/
3) Struggled to find any examples from Google of people doing this kind of SSO. Lots of links about people using SAML as a Django backend.
Question
In the dropbox admin settings I can add my X509 certificate and the login link. This means that when you try to login into Dropbox using SSO it nicely forwards you to my Django site's login page using a GET request with a SAMLRequest in the querystring.
However, my understanding is that I now need to, once the user is authenticated on the Django site, fire a POST request back to Dropbox at their SAML login link with a SAMLResponse in the post data. Using the second resource above I believe I can create the SAMLResponse xml but I am unsure how to redirect the user to the dropbox SAML login link with the SAML data from my Django view.
Any help much appreciated.
Managed to get the functionality I needed using django-saml2-idp https://github.com/peopledoc/django-saml2-idp
Good documentation on installing here: https://github.com/peopledoc/django-saml2-idp/blob/master/doc/INSTALL.txt
Settings in the Dropbox Admin console required the X509 certificate and then the login url set to: https://****.com/idp/login
Note that I had issues installing the M2Crypto dependency so used an Ubuntu package via:
sudo apt-get install python-m2crypto
Additionally I'm using Django 1.9.6 so needed to make overrides to the views.py, urls.py, and registry.py files to make them compatible (various import statements needed updating and the urls changed to the new list format rather than using patterns).
Created a Dropbox Processor as follows:
import base64
import zlib
from saml2idp import base
from saml2idp.xml_render import _get_assertion_xml
def get_assertion_dropbox_xml(parameters, signed=False):
return _get_assertion_xml(ASSERTION_DROPBOX, parameters, signed)
ASSERTION_DROPBOX = (
'<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" '
'ID="${ASSERTION_ID}" '
'IssueInstant="${ISSUE_INSTANT}" '
'Version="2.0">'
'<saml:Issuer>${ISSUER}</saml:Issuer>'
'${ASSERTION_SIGNATURE}'
'${SUBJECT_STATEMENT}'
'<saml:Conditions NotBefore="${NOT_BEFORE}" NotOnOrAfter="${NOT_ON_OR_AFTER}">'
'<saml:AudienceRestriction>'
'<saml:Audience>${AUDIENCE}</saml:Audience>'
'</saml:AudienceRestriction>'
'</saml:Conditions>'
'<saml:AuthnStatement AuthnInstant="${AUTH_INSTANT}"'
'>'
'<saml:AuthnContext>'
'<saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml:AuthnContextClassRef>'
'</saml:AuthnContext>'
'</saml:AuthnStatement>'
'${ATTRIBUTE_STATEMENT}'
'</saml:Assertion>'
)
class Processor(base.Processor):
def _decode_request(self):
"""
Decodes _request_xml from _saml_request.
"""
self._request_xml = zlib.decompress(base64.b64decode(self._saml_request), -15)
def _format_assertion(self):
self._assertion_xml = get_assertion_dropbox_xml(self._assertion_params, signed=False)
Which you register in your settings.py file as follows:
SAML2IDP_CONFIG = {
'autosubmit': True,
'certificate_file': '/****/certificate.pem',
'private_key_file': '/****/private-key.pem',
'issuer': 'https://www.****.com',
'signing': True,
}
sampleSpConfig = {
'acs_url': 'https://www.dropbox.com/saml_login',
'processor': 'dropbox.Processor',
}
SAML2IDP_REMOTES = {
'sample': sampleSpConfig,
}
Works like a dream. Hope this helps somebody out there.

grails 3.0 facebook plugin spring social facebook using default appId 962223610477458

I'm using the
http://splix.github.io/grails-spring-security-facebook/index.html
java version "1.8.0_91"
Grails Version: 3.0.9 & Groovy Version: 2.4.5
I'm not sure where is is being inserted at. I've added the appid to application.yml, application.groovy, src\main\resources\application.properties.
````
DEBUG com.the6hours.grails.springsecurity.facebook.SpringSecurityFacebookGrailsPlugin - Facebook security config: [appId
:********, secret:********, apiKey:Invalid, domain:[classname:com.spontorg.FacebookUser, appUserConnectionPropertyName:u
ser], useAjax:true, autoCheck:true, jsconf:fbSecurity, permissions:[email, user_friends, public_profile], taglib:[langua
ge:en_US, button:[text:Login with Facebook], initfb:true], autoCreate:[enabled:true, roles:[ROLE_USER, ROLE_FACEBOOK]],
filter:[json:[processUrl:/j_spring_security_facebook_json, type:json, methods:[POST]], redirect:[redirectFromUrl:/j_spri
ng_security_facebook_redirect], processUrl:/j_spring_security_facebook_check, type:redirect, position:720, forceLoginPar
ameter:j_spring_facebook_force], beans:[:], host:localhost]
....
DEBUG com.the6hours.grails.springsecurity.facebook.FacebookAuthUtils - Redirect to http://127.0.0.1:8080/j_spring_securi
ty_facebook_check
`````
afterwards the URL redirect is
````
Location:https://www.facebook.com/dialog/oauth?client_id=962223610477458&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fj_spring_security_facebook_check&scope=email%2Cuser_friends%2Cpublic_profile&state=0-c68ca
````
then i get an error 72, and some message about the app is setup for public access, etc.
WELP...
It was me, i must have copy/pasted that in and never looked closely enough. IDK?
I checked the source code & it was pretty clearly pulling that value, rechecked and DOH!
finally got it, you need to match the host: with the value you put in ont the facebook app or it pukes again with a different error.
grails:
plugin:
springsecurity:
facebook:
appId: '###########'
secret: 'asfd!##$asfdasfd!#'
domain:
classname: 'com.domain.FacebookUser'
host: live.yourdomain.com
filter:
type: redirect
permissions: ['email','user_friends','public_profile']

redirect_uri facebook graph api with cakephp

I need to share a page from my php website to user's facebook wall. If user is not logged into facebook, my website redirects to the facebook login page using
$user = $facebook->getUser();
if($user) {
$result = $facebook->api(
'/me/feed/',
'POST',
array('access_token' => $this->access_token, 'link'=>'google.com', 'message' => 'Test link')
);
$this->Session->setFlash('Your link has been succesfully posted on your wall');
$this->redirect($this->referer());
}else {
$login_url_params = array(
'req_perms' => 'publish_stream',
'redirect_uri' => 'localhost/pictrail' //thts the same path I gave to my facebook app
);
$login_url = $facebook->getLoginUrl($login_url_params);
header("Location: {$login_url}");
exit();
}
So, when the user is not logged into facebook .. it redirects to facebook for the user to log in, afterwards it redirects to localhost/pictrail regardless of the url i put in there. I want to redirect it to say localhost/pictrail/images/param ... how can i achieve this? I tried 'localhost/pictrail/images/99' but it didn't work. Everything works fine when the user is logged into facebook.
You cannot redirect from Facebook to localhost as it's not a valid address.
The way that I got around this, for development, was to edit my hosts file and replace the domain with my local ip.
www.example.com 127.0.0.1
Then you can redirect to www.example.com from your Facebook app and it will render your local development version.
Be sure to add this domain to your local server's vhost or similar.
Sorry I misread your question. To change the Facebook redirect url you need to change it in your Facebook app. So you'd have to pass a custom field through to Facebook and then tack it back on afterwards.
Have a look through this, https://developers.facebook.com/docs/authentication/server-side/