I'm use facebook-sdk-0.4.0
I trying run from my server
access_token = get_app_access_token(settings.FACEBOOK_APP_ID, settings.FACEBOOK_API_SECRET)
graph = GraphAPI(access_token)
response = graph.put_wall_post(profile_id='274460312618957', message=message, attachment={'link':link, })
But have error
(#200) The user hasn't authorized the application to perform this
action
I have admin-rules of this page (274460312618957)
I have admin-rules of this APP settings.FACEBOOK_APP_ID
Way error (#200) ??
You need publish_stream permission for your app in order to create posts as detailed here. As to why you get a response code 200, they are detailed here
Related
Using Keycloak with python and flask for identity and access management.
here's the part of the code where the issue occurs:
from keycloak import Client
app = flask(__name__)
kc=Client()
.
.
.
app.route('/login')
def login():
.
.
.
access_token = kc.access_token
userinfo = kc.fetch_userinfo(access_token) #the main issue
session['user'] = userinfo
return jsonify(userinfo)
if __name__ == "__main__":
app.run()
so with the "userinfo" part, the error occurs saying:
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: http://localhost:8080/auth/realms/linkedin_login/protocol/openid-connect/userinfo
if you have experience with keycloak, do you know if anything has to be altered to authorize in the use of userinfo in keycloak?
Thank you!
if your Client() from Keycloak is a KeycloakAdmin instance
(i'm using https://pypi.org/project/python-keycloak/ )
then the error probably comes from trying to access user information using administration credentials.
if your Client() is a KeycloakOpenID again from (https://pypi.org/project/python-keycloak/ ) then it might be a permission problem. You can check in the keycloak interface that the User you set up has Role Mapping>realm-management>realm-admin set (or something equivalent depending of the rights you want to give him).
in any case, a very usefull documentation can be found at https://www.keycloak.org/docs/latest/server_admin/index.html
last and this might be off-topic but if you plain to access specific custom fields from the user infos, the Client Scopes panel will help you add them.
I'd like to connect a chatbot made in python and deployed on aws lambda to a facebook page.
this is my code to verifly connection to facebook
def webhook(event, context):
# #debug
print("event:" )
print(event)
# print("context")
# print(context)
#handle webhook challenge
if keys_exist(event, ["queryStringParameters"]):
print("Veriflying stuff")
v_token = str(find_item(event, 'hub.verify_token'))
print("token :")
print (v_token)
challenge = int(find_item(event, 'hub.challenge'))
print ("challenge")
print(challenge)
if (os.environ['verify_token'] == v_token):
print ("returning stuff")
return (challenge)
But facebook says The URL couldn't be validated. Callback verification failed with the following errors: HTTP Status Code = 502; HTTP Message = Bad Gateway
I have created the urls with serverless. It works well when i do a get request from the browser.
I have given the same url in the facebook Webhook page. And made sure the validation and Verify Token are correct.
I have tried a few things I saw online. But i dont understand a few of them like this one
Facebook Messenger API "URL COULD NOT BE VALIDATED"
I dont understand if I nned a cert file for this?
AND "The URL could not be validated", facebook api error says to give path to a php. Which I dont even use?
I have found the problem.
Facebook also now required the status code of the request.
if keys_exist(event, ["queryStringParameters","hub.verify_token","hub.challenge"]):
print("subscribe to webhook invoked")
v_token = str(find_item(event, 'hub.verify_token'))
challenge = find_item(event, 'hub.challenge')
if ("strongtoken" == v_token):
response = {
"statusCode": 200,
"body": str(challenge)
}
print(challenge)
return response
I am using python-social-auth for authentication with social networks.
I have installed and configured everything. In the last step, I added these two action links:
Login with Facebook
Login with Instagram
Facebook login is working fine but instagram is giving me the following error:
{"code": 400, "error_type": "OAuthException", "error_message": "Redirect URI does not match registered redirect URI"}
in my settings.py I have these:
SOCIAL_AUTH_INSTAGRAM_KEY = 'my_key'
SOCIAL_AUTH_INSTAGRAM_SECRET = 'my_secret'
and
INSTAGRAM_REDIRECT_URI = 'http://localhost:8000/shops/edit'
the most interesting part is that if I try to do this without python-social-aut, i.e. using these configurations:
INSTAGRAM_CLIENT_ID = get_env_setting('INSTAGRAM_CLIENT_ID')
INSTAGRAM_CLIENT_SECRET = get_env_setting('INSTAGRAM_CLIENT_SECRET')
INSTAGRAM_REDIRECT_URI = get_env_setting('INSTAGRAM_REDIRECT_URI')
It is just working fine.
I am thinking it has something to do with that python-social-auth app.
How can I fix it?
Try to set SOCIAL_AUTH_INSTAGRAM_REDIRECT_URL for example
SOCIAL_AUTH_INSTAGRAM_REDIRECT_URL = 'http://localhost:8000/complete/instagram'
and check redirect uri in you instagram client settings.
I'm consistently getting an "Invalid response from Facebook" error when authenticating over Facebook with Oauthlib when building off of the sample code here.
I've outlined the sections of relevant code below.
Setup:
Setting up the Oauth request object.
Not pictured: Navigational routes and Flask app initialization.
from flask_oauthlib.client import OAuth, OAuthException
oauth = OAuth()
facebook = oauth.remote_app('facebook',
base_url='https://graph.facebook.com/',
request_token_url=None,
access_token_url='/oauth/access_token',
authorize_url='https://www.facebook.com/dialog/oauth',
consumer_key=config.get("app_id"),
consumer_secret=config.get("app_secret"),
request_token_params={'scope': 'public_profile,email'}
)
#facebook.tokengetter
def get_facebook_token():
if current_user.is_authenticated():
return current_user.get_facebook_token()
else:
return None
Login handler:
Sending users here in order to begin the process, with the url for the facebook callback appended to the root URL.
#app.route('/facebook/login')
def facebook_login():
return facebook.authorize(callback="http://example.com%s" % url_for('facebook_callback'))
Facebook callback, source of the issue:
From here I can garner that a code (presumably the token) is returned but Oauthlib fails to parse it correctly.
#app.route('/facebook/callback')
def facebook_callback(response):
response = facebook.authorized_response()
if response is None:
flash("You denied the request to sign in.", "error")
return redirect(url_for('index'))
if isinstance(response, OAuthException):
flash("Access denied: %s" % response.message, "error")
return redirect(url_for('index'))
# Request fails here, returns the redirect above.
From dumping the request args I can see fairly clearly that after being directed to Facebook and successfully connecting, there is a very long token being returned to the callback along the lines of '?code=1234567890-abcdefghijklmnop', however actually trying to authenticate with this fails with "Invalid response from Facebook".
Here is a sample request dump:
ImmutableMultiDict([('code', 'AQAPedwWavTb_cBx6NVy-qy3AL5YPr780oG5tA1LfITpVwkk-kr_4I0lG6B-vlhcYEubhuKhEM46bPs-1WpWUpJzcWfhkQ64lIkdLm9uSHSqeBHBM_6zw7SDpvVmGK-JKWBpAqRJuBKenl9zslQizthox96104iiul0uYQY67cmZgPXZi9uL-mcgZ5dRj387eKJIjNninBXxwCGgFkg5kLVHYt7t0ktUH58stYlxn2f98AXuSlrIvWsA5NeHsVbM8XY0XQrDrNbCvjDmEwHQGkZ3uZRbyaecN7MAi0bM0TrZzpuQ8j3M34DnQp_v9n4ktM4')])
Having used similar code based off of the Twitter sample that works, I'm thinking this could be a possible library bug due to Facebook API changes, but I would appreciate any pointers!
For anyone who stumbles upon this from Google in the future, I solved this in a solution that can be read here.
Hey there, I solved this issue in a very hacky way which I would not
recommend for production environments, but I eventually found the
issue a few days after my last message.
When you ask Facebook for an access token, it does NOT give you an
access token in the way you might expect. What I assumed to be a
failure on Facebook's side was instead a (perhaps intentional)
formatting error.
What you might expect:
http://example.com/callback?access_token=00000000000
or
http://example.com/callback with the access token passed as a POST
argument in the headers.
What actually happens is that Facebook responds like this:
http://example.com/callback?#access_token=0000000000
Because of this, it is -impossible- for any server side language
to parse it, as the access token will now only be visible to the
browser itself. It is not passed to the backend whatsoever.
Capturing the request:
#app.route('/facebook/translate', methods=['GET'])
def facebook_translate():
# Facebook responds with the access token as ?#access_token,
# rather than ?access_token, which is only accessible to the browser.
# This part is where things get really, really dumb.
return ''' <script type="text/javascript">
var token = window.location.href.split("access_token=")[1];
window.location = "/facebook/callback?access_token=" + token;
</script> '''
Proceeding as usual:
#app.route('/facebook/callback', methods=['GET', 'POST'])
def facebook_callback():
access_token = request.args.get("access_token")
if access_token == "undefined":
flash("You denied the request to sign in.", "error")
return redirect(url_for('index'))
graph = facebooksdk.GraphAPI(access_token)
profile = graph.get_object("me")
I have an app engine web app that would like to automatically write a post to the wall of a facebook application I control (i.e. every time a particular event occurs on the website I would like to update the wall of my facebook application).
This code will be called from a deferred task on the server.
I have been unable to find anything addressing this. Your help would be appreciated.
First thing I did was get my access token with the following code:
https://graph.facebook.com/oauth/access_token?client_id=FACEBOOK_APP_ID&client_secret=FACEBOOK_APP_SECRET&grant_type=client_credentials&scope=manage_pages,offline_access
Using the returned access token this is what I'm running on the server:
form_fields = {
"access_token": FACEBOOK_ACCESS_TOKEN,
"message": tgText
};
form_data = urllib.urlencode(form_fields)
result = urlfetch.fetch(url="https://graph.facebook.com/MYAPP_FACEBOOK_ID/feed",
payload=form_data,
method=urlfetch.POST,
validate_certificate=False,
headers={'Content-Type': 'application/x-www-form-urlencoded'})
But calling this results in:
{"error":{"type":"OAuthException","message":"(#200) The user hasn't authorized the application to perform this action"}}
As an administrator you can grant access to third party apps (e.g. your python app) to post onto your App's Profile Page (http://www.facebook.com/apps/application.php?id=YOUR_APP_ID) using OAuth:
http://developers.facebook.com/docs/authentication/ (Section Page Login)
Once you received an access token you should be able to post to App Profile Page as described here:
http://developers.facebook.com/docs/reference/api/post/ (Section Publishing)
I have a similar app. Facebook can change the code that you're meant to submit as part of the process for gaining an access token. I wrote a simple web page that creates a form with hidden input fields that contain the data required to get Facebook to authorise an app with a user (see http://developers.facebook.com/docs/reference/dialogs/oauth/).
When the user clicks the submit button, the browser does an HTTP GET to Facebook, with an appropriate query string, where the Facebook user is prompted to login (if needed) and authorise the app. If authorised Facebook calls back your redirect_url with the code which you can store in the DataStore to retrieve when needed as part of the "give me an access token" flow.