OAuth2
OAuth2 (GitHub)
This project demonstrates how to implement GitHub OAuth2 authentication in a GoFiber application.
Prerequisites
- Go 1.27+
- A GitHub OAuth App
- Set Authorization callback URL to
http://localhost:8080/oauth/redirect
- Set Authorization callback URL to
Setup
Clone the repository:
git clone https://github.com/gofiber/recipes.git cd recipes/oauth2Copy the example env file and fill in your credentials:
cp .env.example .envInstall dependencies:
go mod download
Running the Application
go run app.goThen open http://localhost:8080 in your browser and click Login with GitHub.
Environment Variables
Create a .env file in the root directory (see .env.example):
# GitHub OAuth2 App credentials
CLIENT_ID=your_github_client_id
CLIENT_SECRET=your_github_client_secretOAuth2 Flow
Browser β GET /oauth/begin
β generates CSRF state, stores in session
β redirects to https://github.com/login/oauth/authorize
GitHub β GET /oauth/redirect?code=...&state=...
β validates CSRF state
β exchanges code for access token via GitHub API
β gives the session a new id
β stores token in session
β redirects to /welcome.html
GET /protected β OAUTHProtected middleware checks session tokenThe new session id keeps the login from being shared. The id that arrives with the callback is not secret: it can be planted in the victim's browser before the login ("session fixation"), and an attacker who knows it would otherwise be logged in as the victim too. With the new id, the old one is removed from the store and stops working.
GitHub answers a bad, expired or already used code with HTTP 200 and a JSON body that has an error field and no access_token. The callback checks for that before it stores anything in the session.
Example: GitHub OAuth2 token exchange
// POST https://github.com/login/oauth/access_token
// with client_id, client_secret, and code
// Response:
// {"access_token":"gho_...","token_type":"bearer","scope":""}Using Google or another provider
The flow is the same for any OAuth2 provider: redirect the user with a random state, validate the state on the callback, then exchange the code for a token. This recipe calls GitHub's token endpoint by hand. For providers with an endpoint definition in golang.org/x/oauth2 (Google, GitHub, Microsoft and others), the library builds the authorization URL and performs the code exchange for you.
To use Google, create OAuth credentials in the Google Cloud console and register http://localhost:8080/oauth/redirect as an authorized redirect URI. Then configure the client:
import (
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
var googleConfig = &oauth2.Config{
ClientID: os.Getenv("GOOGLE_CLIENT_ID"),
ClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"),
RedirectURL: "http://localhost:8080/oauth/redirect",
Scopes: []string{"https://www.googleapis.com/auth/userinfo.email"},
Endpoint: google.Endpoint,
}In OAUTHBegin, replace the hand-built GitHub URL with the library's:
authURL := googleConfig.AuthCodeURL(state)
return ctx.Redirect().Status(fiber.StatusTemporaryRedirect).To(authURL)In OAUTHRedirect, after the state check, replace the manual POST to the token endpoint with an exchange, and use the token to call Google's user info endpoint:
token, err := googleConfig.Exchange(ctx.Context(), code)
if err != nil {
return ctx.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
}
resp, err := googleConfig.Client(ctx.Context(), token).Get("https://www.googleapis.com/oauth2/v1/userinfo")Keep the state validation. It is what protects the callback from cross-site request forgery.