demo-oauth-client icon indicating copy to clipboard operation
demo-oauth-client copied to clipboard

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

Open Jsalaz1989 opened this issue 2 years ago • 2 comments

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.

Jsalaz1989 avatar May 14 '23 18:05 Jsalaz1989

Hello, please read this. this should solve your problem

RezenkovD avatar Jul 15 '23 11:07 RezenkovD

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: @.***>

Jsalaz1989 avatar Jul 15 '23 11:07 Jsalaz1989