The first time I encountered the OAuth mechanism, I was puzzled by a particular question: How does the OAuth provider reach the web app endpoint, such as a service running at localhost?
Here's the thing: When it comes to OAuth provider, it doesn't directly contact your local service. Instead, it leads the user's browser back to your service with an authorization code.
But hold on a second... Doesn't redirection imply calling my service's endpoint?
Here, the crucial point to remember is the fourth one listed below: You'll receive an HTTP 302 response, with a `Location` header pointing to your callback URL.
If you're still feeling unsure, or if you're in the same boat as I was, let's dive deeper:
I'll explain using the GitHub OAuth Provider and animated flow as an example
.
Callback URL: This is a URL in your application where GitHub's OAuth service will redirect the user after they have authorized your application. This URL is provided by you when you redirect the user to GitHub's OAuth service. In your case, it's localhost:8080/github/callback.
Redirecting to GitHub's OAuth service: When your application wants to authenticate a user, it redirects them to GitHub's OAuth service. This is done by creating a URL to GitHub's OAuth service that includes your application's client ID, requested scopes, and the callback URL. This URL is generated by `oAuthConfig.AuthCodeURL(stateToken)` in your code.
User authorizes your application: The user logs in to GitHub and is asked if they want to give your application the permissions it's requesting (the scopes). If they agree, GitHub's OAuth service will redirect them back to your application using the callback URL you provided.
Redirect back to your application: GitHub's OAuth service redirects the user's browser back to your application by sending an HTTP 302 response with a `Location` header set to your callback URL. It appends an authorization code as a query parameter to this URL. The user's browser follows this redirect, making a request to your callback URL with the authorization code in the query string.
Your application exchanges the authorization code for an access token: Your application extracts the authorization code from the query string and makes a server-to-server request to GitHub's OAuth service to exchange the authorization code for an access token.
Summary
So, GitHub's OAuth service doesn't directly call your callback URL. Instead, it relies on the user's browser to make a request to your callback URL with the authorization code. This is why the callback URL must be a URL that the user's browser can reach.