admin管理员组文章数量:1313121
I've written up a simple python web app meant to parse someone's school schedule and add it to their Google Calendar. It was working perfectly locally, but due to the nature of InstalledAppFlow and the local server that it runs, I couldn't authenticate when running in a Docker container, in WSL, or (I'm assuming) on a server that I'd host it on. I spent ages trying to fix this and finally gave up. As a result I've switched to Flow, which I believe is meant for web apps. However, I'm still having constant issues with authentication. In my current iteration it is redirecting to my site after I click through the authentication page and not writing the token.json file, so authentication is never completed.
I'd like to fix this so that when a user tries to take an action on my site, it will automatically open the authentication page (if their credentials are expired/nonexistent), then return to the site after authentication is complete, having written the token.json file, allowing them to now add events to their calendar. I think I've been looking at this for far too long, however, and don't know what to do at this point. Any help would be much appreciated.
Here is my authentication function.
SCOPES = os.getenv("SCOPES")
def authenticate_google():
"""Authenticate and return a Google Calendar API service instance."""
creds = None
# Token file stores the user's access and refresh tokens
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If no credentials are available, prompt the user to log in
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = Flow.from_client_secrets_file(
os.getenv("GOOGLE_CREDENTIALS_PATH"),
SCOPES,
)
flow.redirect_uri = os.getenv("REDIRECT_URI")
auth_url, _ = flow.authorization_url(
access_type="offline",
include_granted_scopes="true",
prompt="consent"
)
webbrowser.open(auth_url, new=1, autoraise=True)
flow.fetch_token(authorization_response=request.url)
creds = flow.credentials
with open("token.json", "w") as token:
token.write(creds.to_json())
try:
# Build the Calendar API service
service = build('calendar', 'v3', credentials=creds)
return service
except HttpError as error:
print(f"Build failed: {error}")
And here is my .env file if that helps:
SCOPES=
GOOGLE_CREDENTIALS_PATH=credentials.json
REDIRECT_URI=http://127.0.0.1:5000/
REDIRECT_PORT="5000"
Originally the redirect_uri was at port 55481, but then instead of redirecting it was failing to load anything...
本文标签: pythonHow can I authenticate with Google39s OAuth2 in my webappStack Overflow
版权声明:本文标题:python - How can I authenticate with Google's OAuth2 in my webapp? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741887663a2403117.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论