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

Getting Started

Minimal Setup

  1. Installation

    composer require ekapusta/oauth2-esia
    

    Add the service provider to config/app.php:

    Ekapusta\Oauth2Esia\Oauth2EsiaServiceProvider::class,
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Ekapusta\Oauth2Esia\Oauth2EsiaServiceProvider" --tag="config"
    

    Update .env with your ESIA credentials (Client ID, Secret, and Redirect URI).

  3. First Use Case: Authentication Flow Redirect users to ESIA for authentication:

    use Ekapusta\Oauth2Esia\Facades\Oauth2Esia;
    
    $authUrl = Oauth2Esia::getAuthorizationUrl();
    return redirect()->to($authUrl);
    

    Handle the callback in your route:

    Route::get('/esia/callback', function (Request $request) {
        $token = Oauth2Esia::getAccessToken($request->query('code'));
        $userData = Oauth2Esia::getUserData($token);
        // Store $userData in session/database
    });
    

Implementation Patterns

Workflows

  1. Multi-Step Authentication

    • Use getAuthorizationUrl() to initiate OAuth flow.
    • Capture the code in the callback, then exchange it for a token.
    • Fetch user data with getUserData($token).
  2. Token Management

    • Store tokens securely (e.g., encrypted in the database).
    • Refresh tokens when expired:
      $refreshedToken = Oauth2Esia::refreshAccessToken($refreshToken);
      
  3. User Data Handling

    • Normalize ESIA’s response (e.g., personal_code, first_name) into your user model:
      $user = User::updateOrCreate(
          ['esia_personal_code' => $userData['personal_code']],
          [
              'first_name' => $userData['first_name'],
              'last_name'  => $userData['last_name'],
          ]
      );
      
  4. Integration with Laravel Sessions

    • Attach ESIA data to the session after authentication:
      session(['esia_user' => $userData]);
      

Common Use Cases

  • Single Sign-On (SSO): Redirect users to ESIA for authentication, then seamlessly log them into your app.
  • Profile Completion: Pre-fill forms with ESIA data (e.g., address, tax ID).
  • API Proxy: Use ESIA tokens to fetch additional data (e.g., tax records) via ESIA’s API.

Gotchas and Tips

Pitfalls

  1. Redirect URI Mismatch

    • Ensure the redirect_uri in your config matches the callback URL in ESIA’s developer portal. Mismatches cause invalid_redirect_uri errors.
  2. Token Expiry

    • ESIA tokens expire quickly (typically 1 hour). Always handle token_expired errors by refreshing the token or re-authenticating.
  3. Scope Restrictions

    • ESIA may reject requests if scopes aren’t pre-approved in their dashboard. Test with minimal scopes first.
  4. Rate Limiting

    • ESIA may throttle requests. Cache user data (e.g., with Laravel’s cache) to avoid repeated API calls.

Debugging

  • Enable Logging Add to config/oauth2-esia.php:

    'debug' => env('ESIA_DEBUG', false),
    

    Check storage/logs/laravel.log for OAuth errors.

  • Validate Responses Use dd($userData) to inspect raw ESIA responses. Fields may vary by endpoint.

Extension Points

  1. Custom User Mapping Override the default data mapping in a service:

    Oauth2Esia::setUserMapper(function ($data) {
        return [
            'tax_id' => $data['tax_id'] ?? null,
            // Custom logic
        ];
    });
    
  2. Token Storage Extend the package to store tokens in a custom repository:

    Oauth2Esia::setTokenRepository(new YourTokenRepository());
    
  3. Webhook Integration Use ESIA’s webhooks (if supported) to receive real-time updates (e.g., user profile changes).

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
andydefer/laravel-cluster
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