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

Auth Vk Laravel Package

baks-dev/auth-vk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require baks-dev/auth-vk
    
  2. Configure VK App

    • Register a new app in VK Developer.
    • Set Base Domain and Trusted Redirect URL (e.g., https://your-app.dev/auth/vk/callback).
    • Extract Client ID and generate a PKCE Code Verifier (use PKCE Generator).
  3. Update .env

    VK_CLIENT_ID=your_client_id_here
    VK_CODE_VERIFIER=your_generated_verifier_here
    
  4. Run Asset & DB Setup

    php bin/console baks:assets:install
    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  5. First Use Case Add the VK auth route to your routes/web.php:

    use BaksDev\AuthVk\AuthVkController;
    
    Route::get('/auth/vk', [AuthVkController::class, 'redirectToVk'])->name('auth.vk.redirect');
    Route::get('/auth/vk/callback', [AuthVkController::class, 'handleVkCallback'])->name('auth.vk.callback');
    

Implementation Patterns

Workflow Integration

  1. Authentication Flow

    • Trigger VK auth via AuthVkController::redirectToVk() (handles OAuth redirect).
    • VK redirects to your callback URL with an auth_code.
    • The controller exchanges the code for a token and fetches user data.
  2. User Mapping

    • The package expects a User model with vkId and vkEmail fields (created via migrations).
    • Extend BaksDev\AuthVk\Services\UserMapper to customize user creation/updating:
      // config/packages/baks_auth_vk.yaml
      baks_auth_vk:
          user_mapper: App\Services\CustomVkUserMapper
      
  3. Session Handling

    • Uses Symfony’s security component. Ensure your security.yaml includes:
      firewalls:
          main:
              form_login: ~
              vk_auth: ~  # Enables VK auth provider
      
  4. Customizing Token Exchange

    • Override BaksDev\AuthVk\Services\VkAuthService to modify token requests:
      public function getToken(string $code): array
      {
          $response = Http::post('https://oauth.vk.com/access_token', [
              'client_id' => config('services.vk.client_id'),
              'client_secret' => config('services.vk.client_secret'), // Add if needed
              'code' => $code,
              'redirect_uri' => route('auth.vk.callback'),
              'grant_type' => 'authorization_code',
          ]);
          return $response->json();
      }
      
  5. Multi-Tenant Support

    • Attach tenant ID to the VK user payload if using a multi-tenant setup:
      // In your UserMapper
      public function mapUser(array $vkData): User
      {
          $vkData['tenant_id'] = request()->tenantId; // Example
          return User::updateOrCreate(['vkId' => $vkData['id']], $vkData);
      }
      

Gotchas and Tips

Common Pitfalls

  1. PKCE Validation

    • Ensure VK_CODE_VERIFIER is exactly the same as the one generated (case-sensitive).
    • If using a cache, store the verifier with a short TTL (e.g., 5 minutes).
  2. Redirect URI Mismatch

    • VK’s callback must match the Trusted Redirect URL in your app settings.
    • Test locally with https://your-app.test (not localhost).
  3. Missing User Fields

    • The migration adds vkId and vkEmail to the users table. If your User model uses different field names, override the mapper.
  4. Token Expiry

    • VK tokens expire after 1 hour. Cache the token or refresh it silently:
      // In VkAuthService
      public function getFreshToken(): array
      {
          if ($this->isTokenExpired()) {
              return $this->getToken($this->getStoredAuthCode());
          }
          return $this->getCachedToken();
      }
      
  5. Error Handling

    • VK returns errors in the error field (e.g., access_denied). Log these:
      try {
          $token = $this->getToken($code);
      } catch (\GuzzleHttp\Exception\RequestException $e) {
          $response = json_decode($e->getResponse()->getBody(), true);
          throw new \RuntimeException($response['error_description'] ?? 'VK auth failed');
      }
      

Debugging Tips

  1. Enable VK Debug Mode Add ?scope=email,offline to the auth URL to force email scope and offline access:

    // In AuthVkController
    public function redirectToVk()
    {
        return redirect()->to('https://oauth.vk.com/authorize?' .
            http_build_query([
                'client_id' => config('services.vk.client_id'),
                'redirect_uri' => route('auth.vk.callback'),
                'response_type' => 'code',
                'scope' => 'email,offline',
                'state' => bin2hex(random_bytes(16)),
                'code_challenge' => $this->generateCodeChallenge(),
                'code_challenge_method' => 'S256',
            ]));
    }
    
  2. Log VK Responses Add logging to VkAuthService:

    public function getUserData(string $accessToken): array
    {
        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $accessToken,
        ])->get('https://api.vk.com/method/users.get', [
            'access_token' => $accessToken,
            'v' => '5.131',
            'fields' => 'id,email',
        ]);
        \Log::debug('VK API Response:', $response->json());
        return $response->json();
    }
    
  3. Test with VK Sandbox Use VK’s sandbox mode for testing:

    VK_SANDBOX_MODE=true
    

Extension Points

  1. Custom User Provider Implement BaksDev\AuthVk\Contracts\UserProviderInterface to fetch users from a custom source:

    class CustomUserProvider implements UserProviderInterface
    {
        public function findByVkId(string $vkId): ?User
        {
            return User::where('external_id', $vkId)->first();
        }
    }
    
  2. Post-Auth Actions Trigger events after VK auth:

    // In AuthVkController
    public function handleVkCallback()
    {
        $user = $this->authService->authenticate();
        event(new VkUserAuthenticated($user));
    }
    
  3. Dynamic Scopes Fetch additional VK fields dynamically:

    // Override VkAuthService
    protected function getUserFields(): array
    {
        return ['id', 'email', 'first_name', 'last_name', 'photo_100'];
    }
    
  4. Rate Limiting Add rate limiting to VK API calls:

    use Symfony\Component\RateLimiter\RateLimiterFactory;
    
    public function __construct(private RateLimiterFactory $rateLimiter)
    {}
    
    public function getUserData(string $accessToken): array
    {
        $this->rateLimiter->createRateLimiter(10, 'second')->consume();
        // ... rest of the method
    }
    
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.
sentix/ai-chatbot
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