Given this hipothetical scenario:
- A React SPA App served from myawesomespa.com
- A Express API listening at myawesomeapi.com
And this motivation:
I want to let people use its Google account to login / signup in my SPA Front End and get access to my API resources.
Here's my proposal. (Question at the end)
User
accesses myawesomespa.com
User
hits a "Login with google" button (which is a link to google's consent page)
User
is redirected to Google Consent Page
(which should be configured with the wanted OAuth2 scopes)
User
accepts the consent
Google
redirects to myawesomespa.com
with an authorization code
SPA
(without user interaction) calls Google
in order to exchange this code for an id_token
.
SPA
stores that id_token
to be sent in headers of every request to myawesomespa.com
Maybe I've misunderstood something on my way, but at this point that id_token
which is a JWT token properly signed by google can act as an AccessToken
.
So, in order to access protected routes in API
, let say for example that User
wants to see its profile:
SPA
calls myawesomeapi.com/user/profile
passing this id_token
in headers as a Bearer Token
API
verifies the id_token
and as a result, it gets the user info directly from Google
(sub
, and other info depending on the scopes consented such as email, picture, etc).
API
searches for a user in DB with that sub
.
- If the user was not found, it is created at this moment
API
returns the user data.
It works in my mind but maybe that's totaly wrong. AFAIK, id_tokens
are not part of OAuth2 standard but of OpenID instead, but I can't find any reasons to avoid using them this way.
So the question: Is this a right approach? What would you change to make it better, simpler, safer?
Links and related questions:
OAuth2 with SPA and API
Google oauth2 and SPA
what is id_token google oauth
How to identify a Google OAuth2 user?
Google Authentication for Backend
question from:
https://stackoverflow.com/questions/65860429/frontend-spa-express-api-and-google-oauth2-0 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…