So I have a backend service (batch service, no user access), everytime I make a request I need to call the token endpoint and send my username/password in the header then it returns an access token and a refresh token.

Then I make my request to /myapi and pass the access token Authentication: bearer {secret}

After a short time the access token expires.

So when I need to get a new access token, why do I bother using the refresh token if I can reauthenticate again using my username/password?


OAuth isn't really focused on use cases like yours. Normally, the authenticating client (in your case, the backend service) does not ever see, much less store, the password. For example, if I got to site https://oauth_sso.example.com/ and it offers me to sign in with Google, when I click that button the page into which I'm entering my Google credentials is a Google page, not an oauth_sso.example.com page (at least, it is supposed to be; watch for phishing attempts!). Google (the "identity provider") then confirms that I want to give oauth_sso.example.com (the "service provider") access to my Google identity (and possibly also other stuff, like contacts) and directs my browser back to https://oauth_sso.example.com with a token that the site can use to get my identity from Google.

It would be very inconvenient for the user to be re-prompted for their password all the time in a scenario like this, but it would also be a bad idea for the identity provider (Google) to need to look up whether the user has granted the service provider access to their account on every request (too many DB hits, makes scaling and using distributed systems really hard). As a compromise, the site gets a short-lived Access token (usually sent in a cookie or Bearer HTTP header) that can be used without any database hits but contains a signed timestamp so the server will reject it after a few minutes, and a refresh token that does cause a database hit (and will be rejected if the user has decided to revoke the service provider's access to their identity) but that is long-lived.

| improve this answer | |

It's a matter of user experience since tokens are usually stored (in the browser's local storage for example). When a user goes back to a site, their browser can fetch that token (locally) and ask for a refresh.

That way they don't need to re-authenticate unnecessarily (provided that the token has an expiration).

| improve this answer | |
  • Ideally, the tokens used by OAuth 2 are not exposed to the user at all. The user is redirected around with an "Authorization Grant," which the Service Provider's backend exchanges for the tokens (access, refresh). These are persisted server side and not in the browser's local storage. – Daniel Szpisjak Feb 5 '19 at 6:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.