Python authlib flask - จะทำอย่างไร authorize_redirect อย่างชัดเจน?

Oct 26 2020

ฉันมีการเข้าสู่ระบบ "การให้สิทธิ์รหัส" ด้วยการรวมขวดอัตโนมัติที่ทำงานได้ดี:

redirect_uri = url_for('authorize', _external=True)
return oauth.myOauth2.authorize_redirect(redirect_uri)

ด้วยเหตุผลบางอย่างฉันตัดสินใจว่าฉันต้องการพยายามทำให้การเปลี่ยนเส้นทางมองเห็นได้ชัดเจนขึ้นอีกเล็กน้อย แสดงให้ผู้ใช้เห็นแอปของฉันสักครู่ก่อนที่จะเปลี่ยนเส้นทางไปยังหน้าการเข้าสู่ระบบที่บางคนอาจไม่คุ้นเคย

ตอนนี้งานประเภทนี้:

redirect_uri = url_for('authorize', _external=True)
aurl = oauth.myOauth2.create_authorization_url(redirect_uri)
# what to do with aurl['state']?
return render_template('redirect.html', delay=2,
                       redirect_notice='Redirecting to login', 
                       redirect_url=aurl['url'])

แต่เมื่อผมนำกลับไปยัง "อนุมัติ" หลังจากเข้าสู่ระบบที่ฉันได้รับซึ่งผมคิดว่าเป็นเพราะฉันไม่ได้บันทึกauthlib.integrations.base_client.errors.MismatchingStateError: mismatching_state: CSRF Warning! State not equal in request and response.aurl['state']

แต่จะทำจริงได้อย่างไร? ฉันมีปัญหาในการอธิบายว่า authorize_redirect ทำงานอย่างไร
อาจจะมีวิธีที่ดีกว่านี้? ความช่วยเหลือใด ๆ ที่ชื่นชม!

คำตอบ

2 lepture Oct 26 2020 at 13:23

มีสองวิธีในการทำงานให้สำเร็จ:

  1. แยก URL จาก.authorize_redirect:
redirect_uri = url_for('authorize', _external=True)
resp = oauth.myOauth2.authorize_redirect(redirect_uri)
url = resp.headers.get('Location')
return render_template('redirect.html', delay=2,
                       redirect_notice='Redirecting to login', 
                       redirect_url=url)
  1. ใช้.save_authorize_dataเพื่อบันทึก CSRF และข้อมูลอื่น ๆ :
redirect_uri = url_for('authorize', _external=True)
rv = oauth.myOauth2.create_authorization_url(redirect_uri)
oauth.myOauth2.save_authorize_data(request, redirect_uri=redirect_uri, **rv)
return render_template('redirect.html', delay=2,
                       redirect_notice='Redirecting to login', 
                       redirect_url=rv['url'])

คุณสามารถเรียนรู้ได้จาก: https://github.com/lepture/authlib/blob/master/authlib/integrations/flask_client/remote_app.py#L51