authlib / demo-oauth-client

Demo for Flask, Django, and Starlette OAuth clients with Authlib>=v0.13
https://docs.authlib.org/en/latest/client/
264 stars 101 forks source link

FastAPI google authlib doesn't work from html (works from swagger) #27

Open Jsalaz1989 opened 1 year ago

Jsalaz1989 commented 1 year ago

Hi,

I'm not getting much help from google or stackoverflow so I hope you can help.

I have Google OAuth working with FastAPI and authlib, following your example and building off the official security tutorial. This is working via FastAPI's built-in swagger UI, and I can see that I'm only able to access my protected routes if I have logged in with my google user via the fastapi.security.OAuth2PasswordBearer form, which is good.

However, I can't replicate this via my "frontend", which is just some html served by fastapi with a button that triggers the typical Google OAuth form. That is, the button contains <a href="/login">Google</a>. This ultimately takes me to my /token endpoint and prints the {"access_token": <my_token>, "token_type": "bearer"}, which seems good.

In reality, once this token is correctly received, I need to redirect to one of my protected routes. In order to redirect, I can't simply use that <a>. Instead, I need to bind an XMLHttpRequest() to onclick that simulate's the href="/login" with a GET and, if that goes well, then redirects to my protected route. But unfortunately that XMLHttpRequest() results in https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=<client_id>&redirect_uri=http%3A%2F%2F127.0.0.1%3A8004%2Fapi%2Fauth%2Fgoogle&scope=openid+email+profile&state=<state>' (redirected from 'http://127.0.0.1:8004/api/auth/login/google') from origin 'http://127.0.0.1:8004' 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 have tried a variety of different headers and referrerPolicy, as well as CORSMiddleware but so far I am unable to simulate the <a> with my XMLHttpRequest() .

To be honest, I'm not sure I'm approaching this the right way. Ultimately I'm just trying to get your example code to work not just via swagger but also via my html.

RezenkovD commented 1 year ago

Hello, please read this. this should solve your problem

Jsalaz1989 commented 1 year ago

I tried various different things from that article without success. I'm now having better luck with fastapi-users.

El sáb, 15 jul 2023, 13:19, Дмитро Рєзєнков @.***> escribió:

Hello, please read this https://fastapi.tiangolo.com/tutorial/cors/. this should solve your problem

— Reply to this email directly, view it on GitHub https://github.com/authlib/demo-oauth-client/issues/27#issuecomment-1636739312, or unsubscribe https://github.com/notifications/unsubscribe-auth/AEKHBXCA5DDEU2Y5EYN2WSLXQJ4FHANCNFSM6AAAAAAYBJY72I . You are receiving this because you authored the thread.Message ID: @.***>