Skip to content

Neo-Ciber94/axum-oauth-sample

Repository files navigation

Axum OAuth Sample

An axum example of authentication using oauth.

preview.mp4

Preview: https://axum-oauth-sample.fly.dev/ (This only allows Google auth)

This example uses:

  • Axum
  • Askama
  • Sqlx (with SQlite)
  • TailwindCSS

And have oauth authentication for these providers:

  • Google
  • Github
  • Discord

Missing features

  • Refresh tokens
  • Token revocation

How to run

Prerequisites

  1. Install dependencies
cargo install
pnpm install # Or remove pnpm-lock.yaml and run `npm install`
  1. Create database and run migrations
mkdir data
sqlx database create
sqlx migrate run
  1. Run
npm run tw:watch
cargo run # In other shell

Docker

Build the image:

docker build . -t axum-oauth
docker run -dp 5000:5000 -e HOST="0.0.0.0" -e PORT=5000 -e BASE_URL="http://localhost:5000" --env-file=.env.docker axum-oauth

This require create a .env.docker file with similar to .env.sample

Authentication workflow

Login

graph TD
  A[Login] -->|"1. Request /api/auth/{provider}/login"| B[Redirect to Provider]
  B -->|"2. Redirect to OAuth provider"| C[Provider Authorization Page]
  C -->|"3. User authorizes"| D["Redirect to /api/auth/{provider}/callback"]
  D -->|"4. Exchange code for token"| E[Token Response]
  E -->|"5. Request user info"| F[Get user information]
  F -->|"6. Create or retrieve user"| G[Database - Create/Retrieve User]
  G -->|"7. Create user session"| H[Database - Create User Session]
  H -->|"8. Remove cookies"| I[Remove CSRF and Code Verifier Cookies]
  I -->|"9. Set session cookie"| J[Set Session Cookie]
  J -->|"10. Redirect to /"| K[Redirect to Home]
Loading

Logout

graph TD
  L[Logout] -->|"1. Request /api/auth/logout"| M[Check session cookie]
  M -->|"2. Delete user session"| N[Database - Delete User Session]
  N -->|"3. Remove session cookie"| O[Remove Session Cookie]
  O -->|"4. Redirect to /"| P[Redirect to Home]
Loading