Я хотел добавить функцию кнопки входа в Google на мою веб-страницу для доступа к профилю пользователя через проверку oAuth ..... Я создал project.py, login. html для выполнения вышеупомянутого. ... Код в файле project.py
@app.route('/login')
def showLogin():
state = ''.join(random.choice(string.ascii_uppercase + string.digits)
for x in xrange(32))
login_session['state'] = state
#return "The current session state is %s" % login_session['state']
return render_template('login.html', STATE=login_session['state'])
@app.route('/gconnect', methods=['GET','POST'])
def gconnect():
# Validate state token
if request.args.get('state') == login_session['state']:
response = make_response(json.dumps('Invalid state parameter.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
# Obtain authorization code
code=request.data
try:
# Upgrade the authorization code into a credentials object
oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
oauth_flow.redirect_uri = 'postmessage'#1st change
**#####Getting Error Here in this Step**
credentials = oauth_flow.step2_exchange(code)
except FlowExchangeError:
response = make_response(
json.dumps('Failed to upgrade the authorization code.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
# Check that the access token is valid.
access_token = credentials.access_token
url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'
% access_token)
h = httplib2.Http()
result = json.loads(h.request(url, 'GET')[1])
# If there was an error in the access token info, abort.
if result.get('error') is not None:
response = make_response(json.dumps(result.get('error')), 500)
response.headers['Content-Type'] = 'application/json'
return response
# Verify that the access token is used for the intended user.
gplus_id = credentials.id_token['sub']
if result['user_id'] != gplus_id:
response = make_response(
json.dumps("Token's user ID doesn't match given user ID."), 401)
response.headers['Content-Type'] = 'application/json'
return response
# Verify that the access token is valid for this app.
if result['issued_to'] != CLIENT_ID:
response = make_response(
json.dumps("Token's client ID does not match app's."), 401)
print ("Token's client ID does not match app's.")
response.headers['Content-Type'] = 'application/json'
return response
stored_access_token = login_session.get('access_token')
stored_gplus_id = login_session.get('gplus_id')
if stored_access_token is not None and gplus_id == stored_gplus_id:
response = make_response(json.dumps('Current user is already connected.'),
200)
response.headers['Content-Type'] = 'application/json'
return response
# Store the access token in the session for later use.
login_session['access_token'] = credentials.access_token
login_session['gplus_id'] = gplus_id
# Get user info
userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
params = {'access_token': credentials.access_token, 'alt': 'json'}
answer = requests.get(userinfo_url, params=params)
data = answer.json()
login_session['username'] = data['name']
login_session['picture'] = data['picture']
login_session['email'] = data['email']
output = ''
output += '<h1>Welcome, '
output += login_session['username']
output += '!</h1>'
output += '<img src="'
output += login_session['picture']
output += ' " style = "width: 300px; height: 300px;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;"> '
flash("you are now logged in as %s" % login_session['username'])
print ("done!")
return output
Интерфейсный код ajax, обрабатывающий действия страницы:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script src="//apis.google.com/js/platform.js?onload=start"> </script>
<!-- END PRE-REQUISITES FOR GOOGLE SIGN IN -->
<script>
function start() {
gapi.load('auth2',function(){
auth2=gapi.auth2.init({
client_id:'*******************.apps.googleusercontent.com'
});
});
};
</script>
</head>
<body> <!-- GOOGLE PLUS SIGN IN BUTTON-->
<div id="signinButton">
<span class="g-signin"
data-scope="openid email"
data-clientid="**************************.apps.googleusercontent.com"
data-redirecturi="postmessage"
data-accesstype="offline"
data-cookiepolicy="single_host_origin"
data-callback="signInCallback"
data-approvalprompt="force"
>
</span>
</div>
<script>
$('#signinButton').click(function(){
auth2.grantOfflineAccess().then(signInCallback);
});
</script>
<div id="result"></div>
<script>
function signInCallback(authResult) {
if (authResult['code']) {
// Hide the sign-in button now that the user is authorized
$('#signinButton').attr('style', 'display: none');
// Send the one-time-use code to the server, if the server responds, write a 'login successful' message to the web page and then redirect back to the main restaurants page
$.ajax({
type: 'POST',
url: '/gconnect?state={{STATE}}',
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
},
processData: false,
data: authResult['code']
});
if (result) {
$('#result').html('Login Successful!</br>'+ result + '</br>Redirecting...')
setTimeout(function() {
window.location.href = "/restaurant";
}, 4000);
} else if (authResult['error']) {
console.log('There was an error: ' + authResult['error']);}
else {
$('#result').html('Failed to make a server-side call. Check your configuration and console.');
}
}};
</script>
<!--END GOOGLE PLUS SIGN IN BUTTON -->
</body>
</html>
Когда я использую этот код, я ' m g получение ошибки внутри блока FlowExchangeError (т.е. не удалось обновить код авторизации) ..... Я думаю, что этот код отлично работает до строки чуть выше credentials = oauth_flow.step2_exchange(code)
, после чего он просто переходит в блок except ..... . Я попробовал решение в этом ответе , но получаю ту же ошибку