OAuth2 (GitHub)
This project demonstrates how to implement GitHub OAuth2 authentication in a GoFiber application.
Prerequisites
- Go 1.21+
- 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.gitcd recipes/oauth2 -
Copy the example env file and fill in your credentials:
cp .env.example .env -
Install dependencies:
go mod download
Running the Application
go run app.go
Then open http://localhost:8080 in your browser.
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_secret
OAuth2 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
→ stores token in session
→ redirects to /welcome.html
GET /protected → OAUTHProtected middleware checks session token
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":""}