I'm using a google authentication based on the following example. Everything was working and then suddendly when I tried to login I started getting this error:
httplib2.ServerNotFoundError ServerNotFoundError: Unable to find the
server at accounts.google.com
Any ideas on what might be wrong?
from flask import Flask, redirect, url_for, session
from flask_oauth import OAuth
# You must configure these 3 values from Google APIs console
# https://code.google.com/apis/console
GOOGLE_CLIENT_ID = '<Client-ID>'
GOOGLE_CLIENT_SECRET = '<Client-secret>'
REDIRECT_URI = '/authorized' # one of the Redirect URIs from Google APIs console
SECRET_KEY = 'development key'
DEBUG = True
app = Flask(__name__)
app.debug = DEBUG
app.secret_key = SECRET_KEY
oauth = OAuth()
google = oauth.remote_app('google',
base_url='https://www.google.com/accounts/',
authorize_url='https://accounts.google.com/o/oauth2/auth',
request_token_url=None,
request_token_params={'scope': 'https://www.googleapis.com/auth/userinfo.email',
'response_type': 'code'},
access_token_url='https://accounts.google.com/o/oauth2/token',
access_token_method='POST',
access_token_params={'grant_type': 'authorization_code'},
consumer_key=GOOGLE_CLIENT_ID,
consumer_secret=GOOGLE_CLIENT_SECRET)
#app.route('/')
def index():
access_token = session.get('access_token')
if access_token is None:
return redirect(url_for('login'))
access_token = access_token[0]
from urllib2 import Request, urlopen, URLError
headers = {'Authorization': 'OAuth '+access_token}
req = Request('https://www.googleapis.com/oauth2/v1/userinfo',
None, headers)
try:
res = urlopen(req)
except URLError, e:
if e.code == 401:
# Unauthorized - bad token
session.pop('access_token', None)
return redirect(url_for('login'))
return res.read()
return res.read()
#app.route('/login')
def login():
callback=url_for('authorized', _external=True)
return google.authorize(callback=callback)
#app.route(REDIRECT_URI)
#google.authorized_handler
def authorized(resp):
access_token = resp['access_token']
session['access_token'] = access_token, ''
return redirect(url_for('index'))
#google.tokengetter
def get_access_token():
return session.get('access_token')
def main():
app.run()
if __name__ == '__main__':
main()
I've had this problem before and the fix was to disable IPv6 on my computer. For some reason Google and IPv6 don't play well together.
If you're on a Mac, the command is:
sudo networksetup -setv6off wi-fi
Make sure to turn it back on when you're done:
sudo networksetup -setv6automatic wi-fi
Related
So during testing, I was able to sign in with 1 spotify account at the login page and receive a correct access code and token. However, when I run and close the app, and run it again, I went on an incognito tab (with no cookies) and was able to successfully sign into a new Spotify account through the same login page (which sends you to authenticate through spotify). But, for some reason, the spotify API sent me the same access code and token as the first user.
Thanks for your help!
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from flask import Flask, request, url_for, session, redirect, render_template
import time
from os import urandom
# App Initialization
app = Flask(__name__)
# Setup Cookies
app.secret_key = urandom(64)
app.config['SESSION_COOKIE_NAME'] = 'A Session Cookie'
TOKEN_INFO = "token_info"
#app.route('/login')
def login():
sp_oauth = create_spotify_oauth()
auth_url = sp_oauth.get_authorize_url()
return redirect(auth_url)
#app.route('/redirect')
def redirectPage():
sp_oauth = create_spotify_oauth()
session.clear()
code = request.args.get('code')
token_info = sp_oauth.get_access_token(code)
# print(token_info)
session[TOKEN_INFO] = token_info
return redirect(url_for('profile', _external=True))
# Universal Functions
def create_spotify_oauth():
return SpotifyOAuth(
client_id = 'INSERT CLIENT ID',
client_secret = 'INSERT CLIENT SECRET',
redirect_uri=url_for('redirectPage', _external=True),
scope='user-library-read user-read-recently-played user-read-playback-position playlist-read-collaborative user-read-playback-state user-top-read playlist-modify-public user-read-currently-playing user-library-read playlist-read-private playlist-modify-private',
)
def get_token():
token_info = session.get(TOKEN_INFO, None)
if not token_info:
raise "exception"
now = int(time.time())
is_expired = token_info['expires_at'] - now < 60
if is_expired:
sp_oauth = create_spotify_oauth()
token_info = sp_oauth.refresh_access_token(token_info['refresh_token'])
return token_info
app.run()
Essentially, the function "get_access_token()" returns an access token if it can find any on your system through environment variables, so this isn't even an issue for my application. It's working as intended.
im quite new to coding but this is barely documented so i need some help.
Im building a flask application but I cant get the google auth flow working.
Im using Pycharm and python version 3.9
My issues are :
I cant find any beginner tutorial that explains how to go through the Auth flow.
I dont understand how to interact with google APis through flask. (i want to use the android-management-api)
I do understand that i need to create a service object but that only works when i can authenticate the google flow and this is where im already stuck for 5 days now.
I already followed the instructions from realpython and MattButton.
when trying these instructions i keep getting errors.
now im getting:
Error: While importing 'app', an ImportError was raised:
Traceback (most recent call last):
File "C:\000 Projects\Applications\PY\flaskProjects\MDM\venv\lib\site-packages\flask\cli.py", line 256, in locate_app
__import__(module_name)
File "C:\000 Projects\Applications\PY\flaskProjects\MDM\app.py", line 5, in <module>
from flask_oauth import OAuth
File "C:\000 Projects\Applications\PY\flaskProjects\MDM\venv\lib\site-packages\flask_oauth.py", line 13, in <module>
from urlparse import urljoin
ModuleNotFoundError: No module named 'urlparse'
Process finished with exit code 2
Can somebody explain me what im doing wrong
my code is below:
from flask import Flask, redirect, url_for, session, request, jsonify, render_template
from datetime import datetime
from flask import Flask, redirect, url_for, session
from flask_oauth import OAuth
import urllib.parse
# You must configure these 3 values from Google APIs console
# https://code.google.com/apis/console
GOOGLE_CLIENT_ID = ''
GOOGLE_CLIENT_SECRET = ''
REDIRECT_URI = '/authorized' # one of the Redirect URIs from Google APIs console
SECRET_KEY = 'development key'
DEBUG = True
app = Flask(__name__)
app.debug = DEBUG
app.secret_key = SECRET_KEY
oauth = OAuth()
google = oauth.remote_app('google',
base_url='https://www.google.com/accounts/',
authorize_url='https://accounts.google.com/o/oauth2/auth',
request_token_url=None,
request_token_params={'scope': 'https://www.googleapis.com/auth/androidmanagement',
'response_type': 'code'},
access_token_url='https://accounts.google.com/o/oauth2/token',
access_token_method='POST',
access_token_params={'grant_type': 'authorization_code'},
consumer_key=GOOGLE_CLIENT_ID,
consumer_secret=GOOGLE_CLIENT_SECRET)
#app.route('/')
def index():
access_token = session.get('access_token')
if access_token is None:
return redirect(url_for('login'))
access_token = access_token[0]
from urllib.request import Request, urlopen
from urllib.error import URLError
headers = {'Authorization': 'OAuth '+access_token}
req = Request('https://www.googleapis.com/oauth2/v1/userinfo',
None, headers)
try:
res = urlopen(req)
except URLError as e:
if e.code == 401:
# Unauthorized - bad token
session.pop('access_token', None)
return redirect(url_for('login'))
return res.read()
return res.read()
#app.route('/login')
def login():
callback = url_for('authorized', _external=True)
return google.authorize(callback=callback)
#app.route(REDIRECT_URI)
#google.authorized_handler
def authorized(resp):
access_token = resp['access_token']
session['access_token'] = access_token, ''
return redirect(url_for('index'))
#google.tokengetter
def get_access_token():
return session.get('access_token')
#app.route('/home')
def home():
return render_template(
'index.html',
title='Home Page',
year=datetime.now().year,
)
#app.route('/devices')
def devices():
return render_template(
'devices.html',
title='Devices',
year=datetime.now().year,
)
#app.route('/policies')
def policies():
return render_template(
'policies.html',
title='Policies',
year=datetime.now().year,
)
#app.route('/enterprises')
def enterprises():
return render_template(
'enterprises.html',
title='Enterprises',
year=datetime.now().year,
)
#app.route('/contact')
def contact():
# """Renders the contact page."""
return render_template(
'contact.html',
title='Contact',
year=datetime.now().year,
message='ICS-Vertex'
)
#app.route('/about')
def about():
return render_template(
'about.html',
title='About',
year=datetime.now().year,
message='Your application description page.'
)
if __name__ == '__main__':
app.run()
Solved!
I found out that there were 2 conflicting libraries that both used the requests name
Flask.requests
Requests
I have the following script written in python
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app, resources=r'/chat', headers='Content-Type')
#app.route("/chat")
def chat():
print(request)
request.get_data()
data = json.loads(request.data)
response = chatbot.get_response(str(data['message']))
response_data = response.serialize()
response = jsonify({'data': response_data})
return response
app.run(host="0.0.0.0", port=8900, debug=True)
I am calling this API from a JavaScript frontend running on http://localhost:8080
I am using Google Chrome and get the following error
Access to XMLHttpRequest at 'http://localhost:8900/chat/' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I also get the following the log message in the Python Console for each request
127.0.0.1 - - [19/Mar/2020 15:12:00] "?[33mOPTIONS /chat/ HTTP/1.1?[0m" 404 -
I am getting really frustrated because even if I change my code to
#app.route("/chat")
def chat():
print(request)
request.get_data()
data = json.loads(request.data)
response = chatbot.get_response(str(data['message']))
response_data = response.serialize()
response = jsonify({'data': response_data})
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'append,delete,entries,foreach,get,has,keys,set,values,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
return response
I still get the same error.
Can you try setting the headers like this instead?
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app, resources=r'/chat', headers='Content-Type')
#app.route("/chat")
def chat():
print(request)
request.get_data()
data = json.loads(request.data)
response = chatbot.get_response(str(data['message']))
response_data = response.serialize()
response = jsonify({'data': response_data})
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Headers'] = 'append,delete,entries,foreach,get,has,keys,set,values,Authorization'
response.headers['Access-Control-Allow-Methods'] = 'GET,PUT,POST,DELETE,OPTIONS'
return response
app.run(host="0.0.0.0", port=8900, debug=True)
I am trying to authenticate my user using facebook oauth but it is throwing a webpage not found error after the user allows my app in facebook.
Here's the code:
from flask import redirect, Flask, url_for, request
app = Flask(__name__)
app.secret_key = 'asd'
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='xxx',
consumer_secret='yyy',
request_token_params={'scope': 'email'}
)
#app.route('/login')
def login():
print(url_for('oauth_authorized'))
return facebook.authorize(callback='www.resoorce.com' + url_for('oauth_authorized'))
#app.route('/oauth_authorized')
#facebook.authorized_handler
def oauth_authorized(resp):
print("asd")
if resp is None:
print(u'You denied the request to sign in.')
return "NOOOO"
print('You were signed in as %s' % resp['screen_name'])
return "YEAH!!!"
if(__name__ == "__main__"):
app.debug = True;
app.run(hostname = '0.0.0.0', port=int(80))
No error was thrown anywhere, just webpage not found.
Im developing small intranet web service. I want authenticate users over kerberos in MS AD or with basic auth. For that reason i need to set two 'WWW-Authenticate' http headers in response 401. How can i do it with Django ?
Should be something like this:
Client: GET www/index.html
Server: HTTP/1.1 401 Unauthorized
WWW-Authenticate: Negotiate
WWW-Authenticate: Basic realm="corp site"
This code overwrite header
def auth(request):
response = None
auth = request.META.get('HTTP_AUTHORIZATION')
if not auth:
response = HttpResponse(status = 401)
response['WWW-Authenticate'] = 'Negotiate'
response['WWW-Authenticate'] = 'Basic realm=" trolls place basic auth"'
elif auth.startswith('Negotiate YII'):
...
return response
I guess a middleware would be best for this task, but in case you have something else in mind, here is the middleware code adjusted to work with your view(which you can very easily still turn into a middleware if you decide to do so):
from django.conf import settings
from django.http import HttpResponse
def basic_challenge(realm=None):
if realm is None:
realm = getattr(settings,
'WWW_AUTHENTICATION_REALM',
'Restricted Access')
response = HttpResponse('Authorization Required',
mimetype="text/plain")
response['WWW-Authenticate'] = 'Basic realm="%s"' % (realm)
response.status_code = 401
return response
def basic_authenticate(authentication):
(authmeth, auth) = authentication.split(' ', 1)
if 'basic' != authmeth.lower():
return None
auth = auth.strip().decode('base64')
username, password = auth.split(':', 1)
AUTHENTICATION_USERNAME = getattr(settings,
'BASIC_WWW_AUTHENTICATION_USERNAME')
AUTHENTICATION_PASSWORD = getattr(settings,
'BASIC_WWW_AUTHENTICATION_PASSWORD')
return (username == AUTHENTICATION_USERNAME and
password == AUTHENTICATION_PASSWORD)
def auth_view(request):
auth = request.META.get('HTTP_AUTHORIZATION', '')
if auth.startswith('Negotiate YII'):
pass
elif auth:
if basic_authenticate(auth):
#successfully authenticated
pass
else:
return basic_challenge()
# nothing matched, still return basic challange
return basic_challenge()