Thanks to visit codestin.com
Credit goes to github.com

Skip to content

zwpaper/mini-oauth

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Mini OAuth - Rust JWT Authentication Demo

A Rust implementation demonstrating OAuth-like authentication flow using JWT tokens with asymmetric cryptography (RS256). This project consists of two servers that work together to provide secure authentication.

Overview

This demo implements a simple OAuth-like flow with:

  • Server A (Auth Server) - Handles user authentication and JWT token generation
  • Server B (Resource Server) - Protects resources and validates JWT tokens
  • Asymmetric JWT - Uses RS256 algorithm with RSA public/private key pairs
  • Cookie-based authentication - JWT tokens are stored in HTTP-only cookies

Authentication Flow

  1. User tries to access a protected resource on Server B
  2. Server B checks for a valid JWT cookie
  3. If no valid JWT found, Server B redirects (302) to Server A for authentication
  4. User authenticates on Server A
  5. Server A creates a JWT token and sets it as an HTTP-only cookie
  6. Server A redirects (302) back to Server B with the JWT cookie
  7. Server B validates the JWT token using the shared public key
  8. If valid, Server B serves the protected resource

Features

  • Asymmetric JWT Signing: Uses RS256 with RSA 2048-bit keys
  • Secure Cookies: HTTP-only cookies with proper domain and path settings
  • Token Validation: Comprehensive JWT validation including audience and expiration
  • Multiple Protected Resources: Demo includes both regular and admin protected areas
  • User-friendly Interface: Simple HTML forms for testing
  • Logging: Comprehensive logging for debugging and monitoring

Quick Start

Prerequisites

  • Rust (latest stable version)
  • Cargo package manager

Installation

# Clone or create the project
cd mini-oauth

# Build the project
cargo build

Running the Demo

Option 1: Run Both Servers (Recommended)

cargo run both

This starts both servers concurrently:

Option 2: Run Servers Separately

Terminal 1 - Start Auth Server:

cargo run server-a

Terminal 2 - Start Resource Server:

cargo run server-b

Testing the Authentication Flow

  1. Start the servers using one of the methods above

  2. Access a protected resource:

  3. Authenticate:

    • You'll see a login form on Server A
    • Use the default credentials (user123) or enter your own
    • Click "Login" or use the quick test links
  4. Access granted:

    • You'll be redirected back to Server B with a JWT cookie
    • The protected resource will be displayed
    • Try accessing http://localhost:3001/admin for another protected area
  5. Logout:

    • Click the "Logout" link to clear the JWT cookie
    • Try accessing protected resources again to see the full flow

API Endpoints

Server A (Auth Server) - Port 3000

  • GET / - Login form
  • GET /login?user_id=<user>&redirect_uri=<uri> - Authenticate user and redirect

Server B (Resource Server) - Port 3001

  • GET / - Home page with links to protected resources
  • GET /protected - Protected resource (requires authentication)
  • GET /admin - Admin area (requires authentication)
  • GET /logout - Logout and clear JWT cookie

Technical Details

JWT Implementation

  • Algorithm: RS256 (RSA Signature with SHA-256)
  • Key Size: 2048-bit RSA keys
  • Claims: Standard JWT claims (sub, aud, exp, iat)
  • Expiration: 1 hour by default
  • Audience: "server_b" for resource server validation

Security Features

  • HTTP-only Cookies: Prevents XSS attacks
  • Secure Domains: Cookies restricted to localhost domain
  • Token Expiration: Time-based token expiration
  • Audience Validation: Prevents token misuse across services
  • Asymmetric Cryptography: Private key for signing, public key for verification

Project Structure

src/
├── main.rs          # Main application entry point
├── crypto.rs        # JWT and cryptographic utilities
├── server_a.rs      # Authentication server implementation
└── server_b.rs      # Resource server implementation

Configuration

Default Settings

  • Server A Port: 3000
  • Server B Port: 3001
  • JWT Expiration: 3600 seconds (1 hour)
  • Cookie Domain: localhost
  • Log Level: INFO

Customization

You can modify the following in the source code:

  • Ports: Change bind addresses in server_a.rs and server_b.rs
  • JWT Expiration: Modify the expires_in_seconds parameter
  • Cookie Settings: Adjust cookie properties in the login handler
  • Key Size: Change RSA key size in crypto.rs

Development

Building

cargo build

Running Tests

cargo test

Code Formatting

cargo fmt

Linting

cargo clippy

Use Cases

This demo is useful for:

  • Learning OAuth flows: Understanding the redirect-based authentication pattern
  • JWT Implementation: Seeing asymmetric JWT signing and verification in action
  • Microservices Auth: Template for service-to-service authentication
  • Cookie-based Auth: Alternative to bearer token authentication
  • Security Testing: Platform for testing authentication vulnerabilities

Security Considerations

⚠️ This is a demo project - Do not use in production without additional security measures:

  • HTTPS: Use TLS in production
  • CSRF Protection: Implement CSRF tokens for state-changing operations
  • Rate Limiting: Add rate limiting to prevent brute force attacks
  • Input Validation: Enhance input validation and sanitization
  • Secure Headers: Add security headers (HSTS, CSP, etc.)
  • Key Management: Use proper key rotation and storage

Troubleshooting

Common Issues

  1. Port Already in Use:

    Error: Address already in use
    

    Solution: Stop any existing servers or change ports in the code

  2. JWT Verification Failed:

    JWT token verification failed
    

    Solution: Check that both servers are using the same key pair

  3. Cookie Not Set:

    • Ensure cookies are enabled in your browser
    • Check that domain settings match (localhost)
  4. Redirect Loop:

    • Clear your browser cookies
    • Restart both servers

Debug Mode

For detailed logging, the application uses the tracing crate with INFO level by default. You can see detailed logs about:

  • JWT token creation and validation
  • Cookie handling
  • Redirect flows
  • Authentication attempts

Contributing

This is a demo project, but contributions are welcome:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

License

This project is provided as-is for educational purposes.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages