Understanding GitHub OAuth: What Happens Behind the Scenes?
I have implemented GitHub OAuth before, but never really understood what was happening behind the scenes. So I decided to explore the complete flow using Go.
I have implemented GitHub OAuth before, but I never really explored what was happening behind the scenes. Last night, an idea came to my mind: how does GitHub OAuth, or any other OAuth provider, actually work internally?
So I started looking things up on Google and using LLMs to understand the overall flow. After going through the documentation and implementation, I finally started getting a clearer picture of how everything works.
Prerequisites: Creating a GitHub App
Before implementing everything, we need to create a GitHub App. For this, go to GitHub Settings, open Developer Settings, select GitHub Apps, and create a new GitHub App.
While creating the app, we need to provide a few details:
- Homepage URL: http://localhost:8080/ (or the port where your backend is running).
- Callback URL: http://localhost:8080/api/v1/auth/github/callback (use the callback URL you have implemented in your backend).
After filling in these details, create the GitHub App and save the configuration.
Setting up the Webhook URL
For the webhook URL, I have a slightly different approach. Since GitHub needs to communicate with our local backend, it cannot directly access localhost.
So, first run your backend and then expose it publicly using ngrok. For example, if your backend is running on port 8080:
ngrok http 8080
Ngrok will generate a public URL. Copy that URL and paste it into the Webhook URL field in your GitHub App settings. Make sure to include the actual webhook route implemented in your backend, not just the base URL.
For example:
https://your-ngrok-url.ngrok-free.app/api/v1/webhooks/github
Also generate a webhook secret and save it in your backend environment variables. This secret will be used to verify that incoming webhook requests actually come from GitHub.
Once everything is configured, you will have the following credentials and details:
- GitHub App ID
- GitHub App slug
- OAuth Client ID
- OAuth Client Secret
- GitHub App Private Key
- GitHub Webhook Secret
- GitHub Callback URL
Keep these credentials safe and never expose your private key or client secret in frontend code or public repositories.
One important thing to understand is that the OAuth Client ID and GitHub App ID are different. We use the App ID and private key for GitHub App authentication, whereas the Client ID and Client Secret are used for the OAuth flow.
Also, localhost works for OAuth callbacks when testing locally in the same browser. We need ngrok mainly for webhooks because GitHub servers need a publicly accessible URL to send events to our backend.
Initializing the GitHub Client
To understand Login with GitHub properly, I decided to implement it using Go, since I have been learning Go recently.
The two packages I am using are
ghinstallation for GitHub App authentication and golang.org/x/oauth2for OAuth authentication.Here is how I initialize my GitHub client:
func New(cfg config.Github) (*App, error) { atr, err := ghinstallation.NewAppsTransport( http.DefaultTransport, cfg.App.IntegrationID, []byte(cfg.App.PrivateKey), ) if err != nil { return nil, fmt.Errorf( "github: parse app private key: %w", err, ) } return &App{ slug: cfg.AppSlug, appsTransport: atr, oauth: &oauth2.Config{ ClientID: cfg.Oauth.ClientID, ClientSecret: cfg.Oauth.ClientSecret, RedirectURL: cfg.RedirectURL, Scopes: []string{ "read:user", "user:email", }, Endpoint: githuboauth.Endpoint, }, http: &http.Client{ Timeout: 10 * time.Second, }, }, nil }
There are two different things happening here.
First, we create an AppsTransport using our GitHub App ID and private key. This allows our backend to authenticate as a GitHub App when communicating with GitHub APIs. When we need to access installation resources, we can use the installation ID to obtain an installation access token.
Second, we configure OAuth using our Client ID, Client Secret, Callback URL and required scopes. This configuration will be used during the user authorization flow.
So, GitHub App authentication and user OAuth authentication are not the same thing, even though we are using them together in our application.
1. Login with GitHub
When a user clicks the Login with GitHub button, we start the authorization process. Here is what happens:
- Generate two random values: state and verifier.
- Store both values in cookies so we can access them later during the callback.
- Generate a PKCE code challenge from the verifier. We use the S256 method to create this challenge.
- Generate the GitHub authorization URL using the state and code challenge.
- Redirect the user to GitHub using that authorization URL.
Now GitHub handles the authorization part. The user will see the authorization page and can approve our application.
But why do we need both state and verifier?
State helps protect our application against CSRF attacks. When GitHub redirects the user back, we compare the returned state with the one we originally generated.
Verifier is part of PKCE (Proof Key for Code Exchange). We do not send the original verifier during the authorization request. Instead, we send its derived code challenge. Later, during the token exchange, we send the original verifier so GitHub can verify that it matches the original challenge.
2. GitHub Callback
After the user approves our application, GitHub redirects them back to our callback URL with two important query parameters:
/api/v1/auth/github/callback?code=abc123&state=xyz789
Now our application needs to verify the request and exchange the authorization code for an access token.
- Get the code and state from the callback URL.
- Check whether GitHub returned an authorization error, for example, if the user denied access.
- Retrieve the original state and verifier from the cookies we stored during login.
- Compare the state from the callback with the state stored in the cookie. If they do not match, reject the request.
- Exchange the authorization code with GitHub using the original PKCE verifier.
- GitHub validates the request and returns an access token if everything is correct.
- Use that access token to request the user's information from GitHub, such as their username, ID and profile details.
- Store the user's information in our database. If the user already exists, retrieve their existing account instead.
- Clear the temporary state and verifier cookies after processing the callback.
- Create our own application session, store the session cookie securely, and redirect the user to the dashboard.
One thing to remember is that the GitHub access token and our application session are two different things. The access token allows us to access authorized GitHub resources, while our own session keeps the user logged in to our application.
Also, since I requested the
user:email scope, I can access the user's email information through GitHub's email API if needed. The email returned by the normal user profile endpoint can be null when the user keeps it private.Final Thoughts
Finally, I started understanding what was actually happening behind the scenes.
During login, we generate the state and PKCE verifier. We send the state and derived code challenge to GitHub. During the callback, we verify the state and use the original verifier to exchange the authorization code for an access token.
After getting the access token, we fetch the user's information, store it in our database and create our own application session.
That is the overall idea behind GitHub OAuth. Something I had implemented before without really understanding how all these pieces worked together!