GithubHelp home page GithubHelp logo

Comments (9)

lepture avatar lepture commented on August 23, 2024

This is a question rather than bug. Please ask it on StackOverflow. Just a quick hint:

The cause:

File "/home/nebularazer/test_app/.venv/lib/python3.6/site-packages/authlib/client/oauth2.py", line 234, in refresh_token
    refresh_token=refresh_token, **kwargs

In refresh_token method, there is a prepare_token_request. My guess: your refresh_token is not a valid token, or there are other invalid parameters in refresh_token method. Please print all the parameters in refresh_token.

from authlib.

nebularazer avatar nebularazer commented on August 23, 2024

Thank you for looking at this.

This is was refresh token receives:
url: https://www.googleapis.com/oauth2/v4/token
refresh_token: None
body:
auth: <authlib.client.oauth2.OAuth2ClientAuth object at 0x7f234126a320>
headers: None
timeout: None
verify: True
proxies: None
kwargs: {'params': {'access_token': 'ya29.GlujBbIie...iyRlg', 'id_token': 'eyJhbGciOi...YQ'}}

This is was prepare_token_request receives:
body:
scope: email profile
refresh_token: 1/I9Z_I9kmQCOg....iFJIASS8xpuipbLdj
kwargs: {'params': {'access_token': 'ya29.GlujBbIie...iyRlg', 'id_token': 'eyJhbGciOi...YQ'}}

from authlib.

lepture avatar lepture commented on August 23, 2024

You see, your kwargs is invalid. Find out why there is a params in kwargs.

from authlib.

lepture avatar lepture commented on August 23, 2024

I don't know why you put a params with access_token in your request, that is weird. Never mind, I just pushed a commit to fix your issue. But your request is really weird.

from authlib.

nebularazer avatar nebularazer commented on August 23, 2024

I found the issue in my side:
I had a method like this and used params as i am used to do with requests. My bad.
But the issue that update_token is not being fired still persists.

@property
def granted_scopes(self):
    if self.token is None:
        return []

    params = {
        'access_token': self.token['access_token'],
        'id_token': self.token['id_token']
    }
    req = oauth.google.post('/oauth2/v2/tokeninfo', params=params)
    if req.ok:
        data = req.json()
        scopes = data['scope'].split()
        return scopes
    else:
        log.info('failed to get scopes')
        return []

from authlib.

lepture avatar lepture commented on August 23, 2024

token_updater will certainly be called. https://github.com/lepture/authlib/blob/master/authlib/client/oauth2.py#L237

from authlib.

nebularazer avatar nebularazer commented on August 23, 2024

It is not called for me because self.token_updater is None.
I included a full example to show this, based on the docs. (These are working client secrets)
env FLASK_APP=main.py FLASK_DEBUG=True flask run

Tested with authlib0.6 and master.

https://github.com/lepture/authlib/blob/master/authlib/flask/client/oauth.py#L173
self.client_kwargs -> {'scope': 'email profile openid'}
...which results in token_updater not being set
https://github.com/lepture/authlib/blob/master/authlib/client/oauth2.py#L237
self.token_updater -> None

import logging
from time import time

from flask import Flask, jsonify, url_for, redirect, session, request
from authlib.flask.client import OAuth
from authlib.client.errors import OAuthException


logformat = '%(asctime)s [%(levelname)s] (%(name)s): %(message)s'
logging.basicConfig(level=logging.DEBUG, format=logformat)
log = logging.getLogger(__name__)

app = Flask(__name__)
app.config.update(
    SECRET_KEY='development',
    GOOGLE_CLIENT_ID='51052937567-0f6sm9dvnn8092pqlrub9mr6no9ln8i5.apps.googleusercontent.com',
    GOOGLE_CLIENT_SECRET='-Zmz39wboqL5-npjiRBXsCBg',
)


def fetch_token():
    log.info('fetching token')
    return session.get('token')


def update_token(token):
    log.info('updateing token')
    session['token'] = token
    return session['token']


oauth = OAuth(app)
oauth.register(
    'google',
    api_base_url='https://www.googleapis.com/',
    access_token_url='https://www.googleapis.com/oauth2/v4/token',
    authorize_url='https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&prompt=consent',
    refresh_token_url='https://www.googleapis.com/oauth2/v4/token',
    fetch_token=fetch_token,
    update_token=update_token,
    client_kwargs={
        'scope': 'email profile openid'
    }
)


@app.route('/')
def index():
    token = session.get('token')
    if token:
        token_is_expired = token['expires_at'] - time() < 0
    else:
        token_is_expired = True

    try:
        resp = oauth.google.get('/oauth2/v2/userinfo')
        profile = resp.json()
    except OAuthException as e:
        profile = e.message

    if token:
        access_token = token.get('access_token')
        id_token = token.get('id_token')
        resp = oauth.google.post(f'/oauth2/v2/tokeninfo?access_token={access_token}&id_token={id_token}')
        tokeninfo = resp.json()
    else:
        tokeninfo = None

    return jsonify(login=url_for('login', _external=True),
                   expire_token=url_for('expire', _external=True),
                   delete_token=url_for('delete', _external=True),
                   profile=profile,
                   token=session.get('token'),
                   tokeninfo=tokeninfo,
                   token_is_expired=token_is_expired,
                   )


@app.route('/login')
def login():
    redirect_url = url_for('authorize', _external=True)
    return oauth.google.authorize_redirect(redirect_url)


@app.route('/authorize')
def authorize():
    token = oauth.google.authorize_access_token()
    session['token'] = token
    return redirect(url_for('index'))


@app.route('/expire')
def expire():
    log.info('setting expires_at...')
    token = session.get('token')
    if token:
        token['expires_at'] = time() - 10
        session['token'] = token
    return redirect(url_for('index'))


@app.route('/delete')
def delete():
    log.info('deleting token from session...')
    session.pop('token', None)
    return redirect(url_for('index'))

edit: code snippet

from authlib.

lepture avatar lepture commented on August 23, 2024

@nebularazer Sorry. You are right. I've just submited a fix.

from authlib.

nebularazer avatar nebularazer commented on August 23, 2024

Thank you very much 😄 👍

from authlib.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.