2 Authentication and Authorization
Jan K9f edited this page 2025-06-04 09:36:55 +02:00

Authentication and Authorization

This page documents the authentication and authorization system of the Casino Gaming Platform.

Overview

The Casino Gaming Platform uses a hybrid authentication system combining custom JWT tokens with OAuth2 social login integration. This provides:

  • Secure user authentication with email/password
  • OAuth2 social login (GitHub, Google)
  • JWT token-based authorization
  • Email verification system
  • Password recovery functionality
  • User profile management
  • Real-time session management

Architecture

┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│                 │    │                  │    │                 │
│    Frontend     │    │  OAuth2 Providers│    │     Backend     │
│   (Angular 20)  │    │ (GitHub, Google) │    │ (Spring Boot 3) │
│                 │    │                  │    │                 │
└─────────────────┘    └──────────────────┘    └─────────────────┘
        │                       │                       │
        └───────────────────────┼───────────────────────┘
                                │
        ┌───────────────────────▼───────────────────────┐
        │           JWT Token Management                │
        │    - Access Tokens (15 min)                   │
        │    - Refresh Tokens (7 days)                  │
        │    - Email Verification Tokens                │
        │    - Password Reset Tokens                    │
        └───────────────────────────────────────────────┘

Authentication Configuration

JWT Token Configuration

  • Access Token Lifespan: 15 minutes
  • Refresh Token Lifespan: 7 days
  • Email Verification Token: 24 hours
  • Password Reset Token: 1 hour
  • Algorithm: RS256 (RSA + SHA-256)

OAuth2 Provider Configuration

GitHub OAuth2

  • Client Type: Public
  • Scope: user:email
  • Redirect URI: http://localhost:4200/auth/oauth-callback

Google OAuth2

  • Client Type: Public
  • Scope: openid email profile
  • Redirect URI: http://localhost:4200/auth/oauth-callback

User Roles and Permissions

The following user roles are defined:

  • USER: Basic authenticated user with game access
  • ADMIN: Administrative user with management capabilities
  • MODERATOR: User with limited admin capabilities

Security Configuration

  • Password Requirements: Minimum 8 characters, alphanumeric
  • Email Verification: Required for account activation
  • Session Management: Stateless JWT-based authentication
  • CORS Configuration: Restricted to frontend domain

Authentication Flow

Email/Password Authentication

  1. User Registration:

    • User fills out registration form
    • Backend validates email uniqueness
    • Account created with email_verified: false
    • Verification email sent with unique token
    • User clicks verification link to activate account
  2. User Login:

    • User enters email and password
    • Backend validates credentials
    • JWT access and refresh tokens generated
    • Tokens returned to frontend and stored in localStorage
    • User redirected to home dashboard
  3. Token Management:

    • Access token included in API requests via HTTP interceptor
    • Automatic token refresh when access token expires
    • Logout clears tokens and invalidates refresh token

OAuth2 Social Login Flow

  1. GitHub/Google Login:

    • User clicks social login button
    • Frontend redirects to OAuth2 provider
    • User authorizes application
    • Provider redirects to callback with authorization code
  2. OAuth2 Token Exchange:

    • Frontend sends authorization code to backend
    • Backend exchanges code for user profile data
    • Account created or linked if existing
    • JWT tokens generated and returned
    • User logged in and redirected to home

Password Recovery Flow

  1. Password Reset Request:

    • User enters email address
    • Backend generates password reset token
    • Reset email sent with secure link
    • User clicks link to access reset form
  2. Password Reset:

    • User enters new password
    • Backend validates reset token
    • Password updated and tokens invalidated
    • User must log in with new password

Backend Token Validation

  1. Token Verification:

    • Frontend includes JWT token in Authorization header
    • Backend validates token signature and expiration
    • User information extracted from token claims
    • Request proceeds if token valid
  2. Token Refresh:

    • When access token expires, frontend uses refresh token
    • Backend validates refresh token and issues new access token
    • If refresh token invalid, user redirected to login

Authorization

Frontend Authorization

The Angular application uses route guards and service-based authentication:

// auth.guard.ts
@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(
    private authService: AuthService,
    private router: Router
  ) {}

  canActivate(): boolean {
    if (this.authService.isAuthenticated()) {
      return true;
    }
    
    this.router.navigate(['/auth/login']);
    return false;
  }
}

// auth.service.ts
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private tokenKey = 'access_token';
  private refreshTokenKey = 'refresh_token';

  isAuthenticated(): boolean {
    const token = localStorage.getItem(this.tokenKey);
    return token && !this.isTokenExpired(token);
  }

  getToken(): string | null {
    return localStorage.getItem(this.tokenKey);
  }

  logout(): void {
    localStorage.removeItem(this.tokenKey);
    localStorage.removeItem(this.refreshTokenKey);
    this.router.navigate(['/auth/login']);
  }
}

Protected routes are configured with guards:

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'auth', loadChildren: () => import('./auth/auth.module') },
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
  { path: 'games', loadChildren: () => import('./games/games.module'), canActivate: [AuthGuard] },
  { path: 'deposit', component: DepositComponent, canActivate: [AuthGuard] }
];

Backend Authorization

The Spring Boot backend uses Spring Security with custom JWT authentication:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .cors(cors -> cors.configurationSource(corsConfigurationSource()))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/auth/**").permitAll()
                .requestMatchers("/api/health").permitAll()
                .requestMatchers(HttpMethod.POST, "/api/deposits/webhook").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            )
            .sessionManagement(session -> 
                session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            )
            .addFilterBefore(jwtAuthenticationFilter(), 
                UsernamePasswordAuthenticationFilter.class);
        
        return http.build();
    }
}

User Registration and Management

Registration Methods

  1. Email/Password Registration:

    • User fills out registration form with username, email, password
    • Backend validates email uniqueness and password strength
    • User account created with email verification required
    • Verification email sent with activation link
    • User must verify email before full account access
  2. OAuth2 Social Registration:

    • User initiates social login (GitHub/Google)
    • Backend receives user profile from OAuth2 provider
    • Account automatically created and verified
    • User logged in immediately after authorization
  3. Account Linking:

    • Existing users can link social accounts to their profile
    • Multiple login methods for same account
    • Profile consolidation and enhanced security

User Profile Management

  • Profile Updates: Users can update username, email (requires re-verification)
  • Password Changes: Secure password update with current password verification
  • Account Deletion: Soft delete with data retention policy
  • Session Management: View and revoke active sessions

Security Considerations

Token Storage and Security

  • Access Tokens: Stored in browser localStorage with 15-minute expiration
  • Refresh Tokens: Stored in localStorage with 7-day expiration
  • Token Content: Contains user ID, roles, and expiration (no sensitive data)
  • Automatic Cleanup: Expired tokens automatically removed
  • Security Headers: CORS, CSP, and HSTS configured for production

CSRF Protection

  • CSRF protection disabled for stateless JWT authentication
  • CORS configured to restrict cross-origin requests
  • SameSite cookie policy for enhanced security

Session Management

  • Stateless Authentication: JWT tokens eliminate server-side session storage
  • Token Refresh: Automatic refresh of access tokens using refresh tokens
  • Session Timeout: Configurable token expiration times
  • Multi-device Support: Users can be logged in on multiple devices
  • Logout: Invalidates refresh token and clears client-side tokens

API Testing and Development

Obtaining Test Tokens

For API testing, authenticate via the API:

  1. Register Test User:

    POST /api/auth/register
    {
      "username": "testuser",
      "email": "test@example.com",
      "password": "password123"
    }
    
  2. Login for Token:

    POST /api/auth/login
    {
      "email": "test@example.com",
      "password": "password123"
    }
    
  3. Use Access Token:

    Authorization: Bearer <access_token>
    

Swagger API Documentation

  1. Open Swagger UI at http://localhost:8080/swagger-ui.html
  2. Click "Authorize" button
  3. Enter the JWT bearer token (include "Bearer " prefix)
  4. Test authenticated API endpoints

Development Tools

  • Mailpit: Email testing at http://localhost:8025
  • Database Console: H2 console for development database inspection
  • Actuator Endpoints: Health checks and metrics at /actuator

Logout Flow

  1. User-Initiated Logout:

    • User clicks "Logout" button in application
    • Frontend calls logout API endpoint
    • Backend invalidates refresh token in database
  2. Token Cleanup:

    • Frontend clears access and refresh tokens from localStorage
    • HTTP interceptor stops including authorization headers
    • User redirected to login page
  3. Automatic Logout:

    • When refresh token expires or is invalid
    • When access token cannot be refreshed
    • Authentication errors trigger automatic logout
  4. Security Logout:

    • Backend can invalidate all user sessions
    • Password changes trigger logout from all devices
    • Suspicious activity can trigger forced logout

Troubleshooting

Common Issues

  1. "Invalid token" errors:

    • Check token expiration time
    • Verify JWT secret configuration
    • Ensure system clocks are synchronized
    • Check token format (Bearer prefix)
  2. "Access denied" errors:

    • Verify user has required roles
    • Check endpoint security configuration
    • Ensure token contains correct claims
  3. OAuth2 authentication failures:

    • Verify OAuth2 client credentials
    • Check redirect URI configuration
    • Ensure OAuth2 provider is accessible
  4. Email verification issues:

    • Check email service configuration
    • Verify SMTP settings in development
    • Check Mailpit for sent emails

Debugging Tips

  1. Examine token contents:

    • Use jwt.io to decode tokens
    • Check claims, expiration, and signature
    • Verify issuer and audience values
  2. Check application logs:

    • Backend logs show authentication events
    • Frontend console shows token errors
    • Network tab reveals API response codes
  3. Database inspection:

    • Check user table for account status
    • Verify email verification status
    • Review refresh token validity
  4. Email testing:

    • Use Mailpit at http://localhost:8025
    • Check email templates and delivery
    • Verify verification link generation

Security Monitoring

  • Failed Login Attempts: Monitor for brute force attacks
  • Token Abuse: Detect unusual token usage patterns
  • Account Enumeration: Prevent email/username discovery
  • Rate Limiting: Implement request rate limiting for auth endpoints