A secure and straightforward example of backend authentication utilizing HttpOnly cookies for enhanced security.
This project serves as a practical demonstration of implementing a secure authentication system. By leveraging HttpOnly cookies, it helps mitigate common web vulnerabilities, providing a robust foundation for your backend services.
- Key Features
- Google Oauth
- Environment Configuration
- Installation Guide
- API Endpoints & cURL Examples
- Secure by Design: Implements HttpOnly cookies to prevent cross-site scripting (XSS) attacks from accessing sensitive cookie data.
- Backend Focused: A clear and concise backend implementation, perfect for learning and integration.
- Easy to Follow: Well-structured and commented code to guide you through the authentication flow.
When a user clicks the Google login button, the app navigates to: http://localhost:4000/auth/google (can be edited in frontend/src/routes/index.ts)
After selecting a Google account, the user gets redirected back to: frontend_url = System.get_env("FRONTEND_URL") || "http://localhost:3000" (as configured in the auth_controller.ex file).
Properly setting up your environment variables is crucial for the application to run correctly. Below are the sample .env configurations for both the frontend and backend components.
# No environment variables are required for the frontend in this example.
DATABASE_URL=postgresql://user:password@localhost:5432/phx-auth
DB_USERNAME=user
DB_PASSWORD=password
DB_HOSTNAME=localhost
DB_NAME=phx-auth
SECRET_KEY_BASE=hash
GUARDIAN_SECRET=hash
GOOGLE_CLIENT_ID=secret-key
GOOGLE_CLIENT_SECRET=secret-key
FRONTEND_URL=http://localhost:3000
Important: Ensure you replace the placeholder values with your actual database credentials and secret keys.
Follow these simple steps to get the project up and running on your local machine.
To install the necessary frontend packages, you have two options:
- Using Bun:
bun install
- Using npm:
npm install
For the backend, you'll need to fetch the Elixir dependencies using mix:
mix deps.getBelow are examples of how to interact with the API endpoints using cURL.
This endpoint creates a new user.
curl -X POST \
-H "Content-Type: application/json" \
-d '{"user": {"email": "[email protected]", "password": "yourpassword"}}' \
http://localhost:4000/api/registerThis endpoint authenticates a user and returns an HttpOnly cookie. We use -c cookie.txt to save the cookie for subsequent requests.
curl -X POST \
-H "Content-Type: application/json" \
-d '{"email": "[email protected]", "password": "yourpassword"}' \
-c cookie.txt \
http://localhost:4000/api/loginThis is a protected endpoint that requires a valid session cookie. We use -b cookie.txt to send the cookie that was saved during login.
curl -X GET \
-b cookie.txt \
http://localhost:4000/api/meThis endpoint invalidates the user's session. It also requires the session cookie to identify which user to log out.
curl -X POST \
-b cookie.txt \
http://localhost:4000/api/logout