Fiber with Google OAuth2
This example demonstrates how to implement Google OAuth2 authentication in a Fiber application.
Prerequisites
- Go 1.25 or higher
- Go modules
Setup
-
Clone the repository:
git clone https://github.com/gofiber/recipes.gitcd recipes/oauth2-google -
Install dependencies:
go mod tidy -
Obtain OAuth credentials from Google Developers Console.
-
Create a
.envfile in the root directory and add your Google OAuth credentials:APP_PORT=3300GOOGLE_CLIENT_ID=your_client_idGOOGLE_CLIENT_SECRET=your_client_secretGOOGLE_REDIRECT_URL=http://localhost:3300/api/auth/google/callback
Running the Application
-
Run the application:
go run main.go -
The server will start on
http://localhost:3300.
Endpoints
| Method | URL | Description |
|---|---|---|
| GET | /api/ | Redirects to Google login URL |
| GET | /api/auth/google/callback | Handles Google OAuth2 callback and returns user's email |
Example Requests
Redirect to Google Login
curl -X GET http://localhost:3300/api/
Google OAuth2 Callback
curl -X GET http://localhost:3300/api/auth/google/callback?state=state&code=code
Security
OAuth2 State Validation (CSRF Protection)
The login handler generates a random state parameter and stores it in an HttpOnly, Secure, SameSite=Lax cookie before redirecting to Google. The callback handler compares the state query parameter returned by Google against the stored cookie value and returns 403 Forbidden if they do not match. This prevents Cross-Site Request Forgery (CSRF) attacks against the OAuth2 flow.