Tuesday, June 20, 2017

How to use OAuth2 to implement a third-party login/register?

Leave a Comment

Here is my plan (authorization code flow) of implementing such login/register logic. (The third-party only provided the OAuth2 API)

First the SPA frontend will send a GET request to the third-party

GET https://www.example.com/oauth2 client_id=dummyclient redirect_uri=https://mysite/callback response_type=code scope=openid 

Then if the user agree to give his/her openid to mysite then the fronend will get a 301 HTTP response.

---> 301 https://mysite/callback?code=dummycode 

Then the browser will redirect the page to mysite/callback and it will reload SPA and expose the code in URL which can be captured by the SPA then it will send the code to the real backend callback.

GET https://mysite/api/real-callback?code=dummycode 

When the backend get the code, it will send the code to the third-party to exchange an access_token. When the backend get the access_token, it will fire an API request to get the user's openid then decide whether to let the user login or register as a new user. At last it will give back a HTTP response to our SPA frontend which contains the access_token in my OAuth2 system or a 401 unauthorized response.

So my question is how to prove that the real callback is invoked by my own clients (Because if some attacker get my frontend embedded client_id then he can fake the OAuth2 request and phishing the user to agree. After that the attacker will get a valid code then he send back the code to my real callback. Finally, he will get the user's access_token in my system.) How can I use OAuth2 to do authentication without the end user's providing additional information like password.

1 Answers

Answers 1

I would suggest you to change the OAuth2 flow to Implicit and ask for both access_token and id_token (OpenID Connect). Your SPA will get the tokens, send the ID token to your backend, which can use it to decide whether it's possible to create such user. The SPA can use the access token to call protected resources.

This way,

  • only the SPA will be an OAuth2 client - tokens will not be used by two applications (SPA and backend),
  • you will have just one redirect URI,
  • you will not need to transfer tokens from the backend to the SPA.

Update: Without OpenID Connect

If you cannot use the id_token, you could send the access_token to your backend and the backend can get the user's username by sending to token to the Introspection endpoint https://tools.ietf.org/html/rfc7662 (from the response username attribute). The username attribute is optional. Your OAuth2 server may return even more info (such as name and email).

This Introspection endpoint requires authentication, so to use it, your backend will have to be a registered OAuth2 client with its own client_id and a secret.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment