This is a sample Flask application demonstrating how to implement "Login with Google" functionality using OAuth 2.0 and the Authlib library.
- User login via Google OAuth 2.0.
- Session management for logged-in users.
- Protected route accessible only after login.
- Logout functionality.
- Secure credential management using environment variables.
- Python 3.7+
- pip (Python package installer)
- Access to Google Cloud Console to obtain OAuth 2.0 credentials.
-
Clone the repository (if you haven't already):
git clone <repository_url> cd <repository_directory>
-
Create and activate a virtual environment:
python -m venv venv # On Windows # venv\Scripts\activate # On macOS/Linux # source venv/bin/activate
-
Install dependencies:
pip install -r requirements.txt
-
Set up Google OAuth 2.0 Credentials:
- Go to the Google Cloud Console.
- Create a new project or select an existing one.
- Navigate to "APIs & Services" > "Credentials".
- Click "Create Credentials" > "OAuth client ID".
- Choose "Web application" as the application type.
- Give it a name (e.g., "Flask OAuth App").
- Under "Authorized JavaScript origins", you don't need to add anything for this server-side flow.
- Under "Authorized redirect URIs", add the callback URL for your application. For local development, this will typically be:
http://localhost:5000/authorizehttp://127.0.0.1:5000/authorize(Ensure this matches theredirect_uriused inapp.py-url_for('authorize', _external=True)will generate this based on how you run the app).
- Click "Create". You will be shown your "Client ID" and "Client Secret".
-
Configure Environment Variables:
- Make a copy of
.env.exampleand name it.env:cp .env.example .env
- Open the
.envfile and replace the placeholder values with your actual Google Client ID and Client Secret obtained in the previous step:GOOGLE_CLIENT_ID="YOUR_GOOGLE_CLIENT_ID_HERE" GOOGLE_CLIENT_SECRET="YOUR_GOOGLE_CLIENT_SECRET_HERE"
- Make a copy of
- Ensure your virtual environment is activated.
- Run the Flask development server:
python app.py
- Open your web browser and navigate to
http://localhost:5000orhttp://127.0.0.1:5000.
You should see a login page. Clicking the "Login with Google" button will redirect you to Google's authentication page. After successful authentication, you will be redirected back to the application and see a welcome message.
app.py: Main Flask application file containing routes and OAuth logic.requirements.txt: Python dependencies.templates/: HTML templates for different pages (login, index, error)..env: Stores your Google OAuth credentials (gitignored)..env.example: Example environment file..gitignore: Specifies intentionally untracked files that Git should ignore.README.md: This file.