Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Oauth2 Esia Laravel Package

ekapusta/oauth2-esia

Laravel/PHP OAuth2 client for Russia’s ESIA (Gosuslugi) authentication. Provides ESIA OAuth flow integration, token handling, and user profile retrieval to add ESIA login to your application with minimal setup.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Use Case Alignment: The ekapusta/oauth2-esia package is tailored for Estonia’s national e-identity authentication system (ESIA), enabling OAuth2-based authentication and retrieval of user personal data (e.g., name, ID code, etc.). This is a niche but critical fit for:
    • Government/PSI (Public Sector Information) integrations (e.g., e-residency, digital services, tax portals).
    • B2G (Business-to-Government) applications requiring verified identity flows.
    • Compliance-heavy systems where legal identity verification is mandatory (e.g., banking, notary services).
  • Architectural Constraints:
    • Monolithic vs. Microservices: Best suited for monolithic Laravel apps or microservices with dedicated auth layers. If using a headless API-first approach, consider wrapping this in a dedicated auth service to isolate ESIA dependencies.
    • State Management: ESIA OAuth2 flows require state/csrf tokens and redirect-based auth. Ensure your frontend (if applicable) supports PKCE or traditional OAuth2 redirects.
    • Data Sensitivity: Personal data (e.g., ID code, address) may trigger GDPR/PIL compliance requirements. Audit logging and encryption (e.g., Laravel’s encryption facade) should be baked in.

Integration Feasibility

  • Laravel Ecosystem Fit:
    • Laravel Passport/Lumen Auth: Can coexist but requires separate OAuth2 providers (ESIA vs. traditional user auth). Use Laravel’s Socialite as a bridge or build a custom Auth Guard for ESIA.
    • Middleware: Leverage Laravel’s middleware pipeline to:
      • Validate ESIA tokens before granting access to routes.
      • Inject user data (e.g., esia_user trait) into controllers.
    • Service Providers: The package likely expects a config-based setup (client ID, redirect URI). Use Laravel’s config/oauth.php or a dedicated esia.php config file.
  • Database Schema:
    • User Model Extension: Extend Laravel’s User model or create a EsiaUser pivot table to store ESIA-specific claims (e.g., personal_code, given_name).
    • Token Storage: Decide between:
      • Database: Store refresh/access tokens in users table or a oauth_tokens table.
      • Cache: Use Laravel’s cache (e.g., Redis) for short-lived tokens (risk: token loss on cache flush).
      • External Store: For high-scale apps, offload to a dedicated token service (e.g., Redis, DynamoDB).

Technical Risk

Risk Area Severity Mitigation
ESIA API Changes High Implement feature flags and versioned endpoints in your API. Monitor ESIA’s status page or changelog.
Token Revocation Medium Use refresh tokens and build a token revocation webhook listener.
CSRF/State Attacks High Enforce strict state binding and validate state params on redirect.
Data Mapping Errors Medium Validate ESIA response schema against your User model (e.g., use Laravel’s ValidatesWhenResolved).
Rate Limiting Medium Implement exponential backoff for ESIA API calls (e.g., Guzzle middleware).
Multi-Tenancy Low If supporting multiple ESIA clients, use tenant-aware config (e.g., esia_clients table).

Key Questions

  1. Auth Flow:
    • Will users authenticate via redirect (web) or API (mobile/headless)? ESIA supports both, but PKCE is mandatory for SPAs/mobile.
    • Do you need silent token refresh (e.g., for background jobs)?
  2. Data Ownership:
    • How will ESIA-provided data (e.g., address) sync with your existing user profiles? (Merge? Overwrite?)
  3. Compliance:
    • Are you subject to eIDAS, GDPR, or Estonian data laws? Audit logs may be required.
  4. Fallbacks:
    • What’s the offline/auth-failure UX? (e.g., "Authenticate via MobileID" as a backup?)
  5. Testing:
    • Do you have access to ESIA’s sandbox environment? (Critical for pre-production testing.)
  6. Monitoring:
    • How will you track auth success/failure rates and token expiration?

Integration Approach

Stack Fit

  • Backend:
    • Laravel 8+ (recommended for dependency injection and middleware).
    • PHP 8.0+ (for named arguments and attributes, if using custom auth guards).
    • Dependencies:
      • league/oauth2-client (base for oauth2-esia).
      • guzzlehttp/guzzle (for HTTP clients).
      • laravel/socialite (optional, for unified auth).
  • Frontend:
    • Blade/PHP: For traditional web apps with redirect flows.
    • Vue/React: Use PKCE (Proof Key for Code Exchange) for SPAs. Example:
      // Example PKCE flow with Axios
      const codeVerifier = generateCodeVerifier();
      const codeChallenge = await generateCodeChallenge(codeVerifier);
      window.location.href = `/esia/auth?code_challenge=${codeChallenge}`;
      
  • Database:
    • MySQL/PostgreSQL: For storing user-ESIA mappings.
    • Redis: For caching tokens (if not using DB).

Migration Path

  1. Phase 1: Proof of Concept (1-2 weeks)
    • Set up a sandbox Laravel app with:
      • ESIA OAuth2 config (esia.php).
      • A /esia/callback route to handle redirects.
      • Basic user model extension.
    • Test with ESIA’s sandbox (if available).
  2. Phase 2: Core Integration (2-3 weeks)
    • Implement Laravel middleware to validate ESIA tokens.
    • Build user sync logic (e.g., EsiaService::syncUser()).
    • Add token refresh logic (e.g., EsiaTokenManager).
  3. Phase 3: Production Readiness (1-2 weeks)
    • Rate limiting: Add Guzzle middleware for ESIA API calls.
    • Monitoring: Log auth events to Sentry/Laravel Log.
    • Fallbacks: Implement backup auth methods (e.g., MobileID).
  4. Phase 4: Scaling (Ongoing)
    • Caching: Offload token storage to Redis.
    • Microservice: Extract ESIA logic into a dedicated auth service if scaling horizontally.

Compatibility

  • Laravel Versions:
    • Tested on Laravel 8/9/10. Avoid Laravel 7 (missing PHP 8 features).
  • PHP Extensions:
    • openssl, curl, json (required for OAuth2).
  • ESIA API Constraints:
    • Redirect URIs: Must be whitelisted in ESIA’s portal.
    • Token Lifetimes: Access tokens expire in 1 hour; refresh tokens in 30 days.
    • Data Fields: ESIA returns a fixed schema (e.g., personal_code, given_name). Extend your User model accordingly:
      class User extends Authenticatable {
          protected $casts = [
              'personal_code' => 'string',
              'esia_token' => 'object',
          ];
      }
      

Sequencing

  1. Configure ESIA Client:
  2. Set Up Laravel:
    • Publish package config:
      php artisan vendor:publish --provider="Ekapusta\Oauth2Esia\EsiaServiceProvider"
      
    • Configure .env:
      ESIA_CLIENT_ID=your_id
      ESIA_CLIENT_SECRET=your_secret
      ESIA_REDIRECT_URI=https://yourapp.com/esia/callback
      
  3. Implement Auth Flow:
    • Web: Use Blade + Auth::loginUsingId() after callback.
    • API: Return ESIA tokens in JWT payload (if using Laravel Sanctum/Passport).
  4. Handle Data:
    • Map ESIA claims to your User model:
      $esiaUser = $esiaService->getAuthenticatedUser($token);
      $user = User::updateOrCreate(
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor