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 Bundle Laravel Package

ekapusta/oauth2-esia-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ekapusta/oauth2-esia-bundle
    

    Register the bundle in config/app.php under providers:

    Ekapusta\OAuth2EsiaBundle\EkapustaOAuth2EsiaBundle::class,
    
  2. Basic Configuration Add ESIA OAuth2 settings to config/packages/ekapusta_oauth2_esia.yaml:

    client_id: "YOUR_SYSTEM_ID"
    redirect_uri: "https://your-app.com/auth/esia/callback"
    signer:
        class_name: Ekapusta\OAuth2Esia\Security\Signer\OpensslCli
        certificate_path: "%kernel.project_dir%/config/esia/public.cer"
        private_key_path: "%kernel.project_dir%/config/esia/private.key"
        private_key_password: "your_private_key_password"
        tool_path: "/usr/bin/openssl"
    
  3. First Use Case: Authentication Flow Use the OAuth2EsiaAuthenticator service to initiate login:

    use Ekapusta\OAuth2EsiaBundle\Security\Auth\OAuth2EsiaAuthenticator;
    
    $authenticator = app(OAuth2EsiaAuthenticator::class);
    $authUrl = $authenticator->getLoginUrl();
    // Redirect user to $authUrl
    

Implementation Patterns

Workflow: OAuth2 Flow Integration

  1. Initiate Login Redirect users to ESIA with pre-signed request:

    $authenticator = app(OAuth2EsiaAuthenticator::class);
    return redirect()->to($authenticator->getLoginUrl());
    
  2. Handle Callback Use the CallbackController (included in the bundle) or implement your own:

    public function callback(OAuth2EsiaAuthenticator $authenticator)
    {
        $user = $authenticator->authenticateRequest($request);
        // Handle authenticated user (e.g., create/update session)
    }
    
  3. Token Management Fetch and validate tokens post-authentication:

    $token = $authenticator->getAccessToken();
    $userInfo = $authenticator->getUserInfo($token);
    

Integration Tips

  • Symfony Security Component Extend AbstractGuardAuthenticator for seamless integration with Symfony’s security system:

    use Ekapusta\OAuth2EsiaBundle\Security\Auth\OAuth2EsiaAuthenticator as BaseAuthenticator;
    
    class CustomEsiaAuthenticator extends BaseAuthenticator
    {
        public function supports(Request $request)
        {
            return $request->isMethod('GET') && $request->getPathInfo() === '/login/esia';
        }
    }
    
  • Environment Variables Store sensitive paths (e.g., private_key_path) in .env:

    ESIA_CERT_PATH=%kernel.project_dir%/config/esia/public.cer
    ESIA_KEY_PATH=%kernel.project_dir%/config/esia/private.key
    

    Reference them in config:

    signer:
        certificate_path: "%env(ESIA_CERT_PATH)%"
    
  • Testing Use the EsiaOAuth2Client service directly for unit tests:

    $client = $this->container->get('ekapusta_oauth2_esia.client');
    $response = $client->fetchAccessToken($code);
    

Gotchas and Tips

Pitfalls

  1. Certificate Validation

    • Issue: ESIA rejects requests with invalid or mismatched certificates.
    • Fix: Ensure certificate_path and private_key_path point to valid, paired files. Verify with:
      openssl x509 -in public.cer -text -noout
      openssl rsa -in private.key -check
      
  2. Redirect URI Mismatch

    • Issue: ESIA rejects callbacks if redirect_uri in config doesn’t match the registered URI.
    • Fix: Double-check the URI in config/packages/ekapusta_oauth2_esia.yaml and register it in the ESIA developer portal.
  3. Openssl CLI Dependency

    • Issue: OpensslCli signer requires openssl binary in PATH.
    • Fix: Specify the full path to openssl in tool_path or ensure it’s in the system PATH.
  4. Token Expiry

    • Issue: Access tokens expire after 1 hour. Refresh tokens are not supported by ESIA.
    • Fix: Cache user data post-authentication or re-authenticate when needed.

Debugging

  • Enable Verbose Logging Add to config/packages/monolog.yaml:

    handlers:
        esia:
            type: stream
            path: "%kernel.logs_dir%/esia.log"
            level: debug
            channels: ["ekapusta_oauth2_esia"]
    

    Then enable the channel in config/packages/ekapusta_oauth2_esia.yaml:

    logging: true
    
  • Check Raw Responses Inspect the raw OAuth2 response for errors:

    $response = $client->fetchAccessToken($code);
    if ($response->isError()) {
        \Log::error('ESIA Error:', ['response' => $response->getBody()]);
    }
    

Extension Points

  1. Custom User Provider Override the default user mapping by extending the EsiaUserProvider:

    use Ekapusta\OAuth2EsiaBundle\Security\User\EsiaUserProvider as BaseProvider;
    
    class CustomEsiaUserProvider extends BaseProvider
    {
        protected function mapUserInfoToUser(array $userInfo)
        {
            return new User([
                'id' => $userInfo['snils'] ?? null,
                'name' => $userInfo['name'] ?? null,
                // Custom logic
            ]);
        }
    }
    

    Register it in config/packages/ekapusta_oauth2_esia.yaml:

    user_provider: App\Security\User\CustomEsiaUserProvider
    
  2. State Management For CSRF protection, implement a custom state generator:

    use Ekapusta\OAuth2EsiaBundle\Security\Auth\StateGeneratorInterface;
    
    class CustomStateGenerator implements StateGeneratorInterface
    {
        public function generate(): string
        {
            return bin2hex(random_bytes(32));
        }
    }
    

    Bind it in services.yaml:

    Ekapusta\OAuth2EsiaBundle\Security\Auth\StateGeneratorInterface: '@App\Security\Auth\CustomStateGenerator'
    
  3. Multi-Tenant Support Dynamically set client_id based on tenant:

    $authenticator->setClientId(Tenant::current()->esiaClientId);
    
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