-
On Frontend
- User clicks
Login With GithubButton. - We redirect user to
https://github.com/login/oauth/authorizewithclient_id,redirect_uriandscopeas query params. - Example
https://github.com/login/oauth/authorize?scope=user:email&client_id=<CLIENT_ID>&state=<state> - Once user allows access github redirect back us to supplied
redirect_uriwithcodeas query parameter. - Example
https://linklet-api.now.sh/api/github/callback?code=34f137a0ea8d9306b7d9&state=JDTzqABd3XYTj8s6GUlOI used
https://linklet-api.now.sh/api/github/callbackthis asredirect_uribefore. - Then we need to send this
codeto our backend.
- User clicks
-
On Backend
- Then we use this
codealong with ourclientId,clientSecretto obtainaccess_tokenandrefresh_token. i.e send post request as shown below on backend side. - Example in node.js
fetch('https://github.com/login/oauth/access_token', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, body: JSON.stringify({ clientId, clientSecret, code, }), }) .then(data => data.json()) .then(json => { console.log(json.access_token) console.log(json.refresh_token) // use this `access_token` to fetch user profile details using this URL https://api.github.com/user?access_token=<access_token> });
- In this we use our previously authenticated
access_tokento get user profile deatails from that service or make other API calls to that service - We may store user data in database
- This ends creating user in database and we may create user session for our backend in order to keep track of authenticated user for our backend
- Then we use this
We may or may not store access_token or refresh_token in our database.
- If we only want to autheticate users then no need of storing them.
- If we want to interact with that service later for eg: In case of facebook we want post something on behalf of user or in case of github create a pullrequest on behalf of user etc.. Then we use this
access_tokento access that service on behalf of that user.
BTW access_token is shortlived i.e it expires after sometime for security reasons. So again we need to ask user to login with that service that would be bad UX, so OAUTH providers provide an easy way i.e refresh_token. We use this token along with our ClientSecret to obtain new access_token and new refresh_token form that service.
This is what i understood.