Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

authentication - Frontend SPA, Express API and Google OAuth2.0

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)

  1. User accesses myawesomespa.com
  2. User hits a "Login with google" button (which is a link to google's consent page)
  3. User is redirected to Google Consent Page (which should be configured with the wanted OAuth2 scopes)
  4. User accepts the consent
  5. Google redirects to myawesomespa.com with an authorization code
  6. SPA (without user interaction) calls Google in order to exchange this code for an id_token.
  7. 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:

  1. SPA calls myawesomeapi.com/user/profile passing this id_token in headers as a Bearer Token
  2. 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).
  3. API searches for a user in DB with that sub.
  4. If the user was not found, it is created at this moment
  5. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...