Authentication - gaulatti/autostrada-frontend GitHub Wiki

Overview

Autostrada uses AWS Cognito for authentication, providing a secure and scalable solution for user management. This document details the authentication flow implementation in the frontend application.

Authentication Components

Core Authentication Services

  1. AWS Amplify Configuration

    • Located in app/root.tsx
    • Configures Cognito user pool settings
    • Sets up OAuth flows with appropriate redirect URIs
  2. Authentication Hooks

    • useAuthStatus: Provides the current authentication state
    • useLogout: Handles user logout and session clearing
    • useSession: Manages the user session and token refresh
  3. Authentication Pages

    • Login page: User sign-in interface
    • Logout page: Session termination confirmation
    • OAuth callback handler: Processes authentication responses

Authentication Flow

1. Initial Application Load

When the application first loads:

  1. The root.tsx component initializes AWS Amplify with the Cognito configuration.
  2. The application checks for an existing authenticated session.
  3. If a valid session exists, the user is directed to the main application.
  4. If no session exists, the user is redirected to the login page.

2. Login Process

The login flow consists of:

  1. User navigates to the login page.
  2. User enters credentials or selects to sign in with an OAuth provider.
  3. AWS Cognito handles the authentication and returns tokens.
  4. The application stores the tokens and redirects to the callback URL.
  5. The callback handler processes the authentication response and updates the Redux store.
  6. Once authenticated, the user is redirected to the main application.
sequenceDiagram
    participant User
    participant Frontend
    participant Cognito
    
    User->>Frontend: Access application
    Frontend->>Frontend: Check for existing session
    alt No session
        Frontend->>User: Redirect to login page
        User->>Frontend: Enter credentials
        Frontend->>Cognito: Authentication request
        Cognito->>Cognito: Validate credentials
        Cognito->>Frontend: Return authentication tokens
        Frontend->>Frontend: Store tokens
        Frontend->>User: Redirect to main application
    else Session exists
        Frontend->>User: Show main application
    end

3. Session Management

After successful authentication:

  1. The application stores authentication tokens in secure storage.
  2. Redux sagas monitor the session state.
  3. The useAuthStatus hook provides authentication state to components.
  4. Token refresh is handled automatically in the background.
  5. Session timeouts redirect users back to the login page.

4. Logout Process

When a user logs out:

  1. User clicks the logout button.
  2. The application calls the useLogout hook.
  3. AWS Amplify clears the authentication tokens.
  4. Redux store authentication state is cleared.
  5. User is redirected to the logout confirmation page.
  6. After confirmation, the user is redirected back to the login page.

Token Handling

Token Types

  1. ID Token: Contains user identity information
  2. Access Token: Used for API authorization
  3. Refresh Token: Used to obtain new tokens when others expire

Security Considerations

  • Tokens are stored securely and never exposed in the URL
  • All tokens have appropriate expiration times
  • Refresh tokens are used to maintain the session without requiring frequent logins
  • HTTPS is enforced for all authentication operations

Protected Routes

Autostrada implements protected routes to secure application content:

  1. Route configuration checks the auth state before rendering protected components.
  2. Unauthorized access attempts are redirected to the login page.
  3. Role-based access control further restricts access based on user permissions.

Integration with Backend API

The authentication flow is integrated with the backend API:

  1. The authenticated user's access token is included in API requests.
  2. The backend validates tokens for API authorization.
  3. Invalid or expired tokens trigger a session refresh or logout.

OAuth Configuration

The OAuth configuration includes:

const config: ResourcesConfig = {
  Auth: {
    Cognito: {
      userPoolId,
      userPoolClientId,
      loginWith: {
        oauth: {
          domain: userPoolDomain,
          scopes: ['email', 'openid', 'profile', 'aws.cognito.signin.user.admin'],
          redirectSignIn: ['http://localhost:5173', fqdn],
          redirectSignOut: ['http://localhost:5173/logout', `${fqdn}/logout`],
          responseType: 'code',
        },
      },
    },
  },
};

Troubleshooting

Common authentication issues and solutions:

  1. Session timeouts: Usually due to token expiration - refresh the token or re-login
  2. Redirect issues: Check OAuth configuration for proper redirect URIs
  3. API authorization failures: Verify token inclusion in API requests
  4. Cross-origin problems: Ensure CORS is properly configured

Implementation Recommendations

When working with the authentication system:

  1. Always use the provided hooks for authentication operations
  2. Don't store sensitive user information in local storage or Redux without encryption
  3. Keep OAuth configuration in sync between frontend, backend, and AWS Cognito
  4. Test authentication flows in both development and production environments