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

aulasoftwarelibre/oauth2-uco

Laravel OAuth2 provider for Universidad de Córdoba (UCO). Adds authentication support for UCO’s OAuth2 service, enabling login and user info retrieval in Laravel/Socialite-based apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require aulasoftwarelibre/oauth2-uco
    

    Ensure php-league/oauth2-client is also installed (this package extends it).

  2. Register Provider In your Laravel config/services.php:

    'uco' => [
        'client_id' => env('UCO_CLIENT_ID'),
        'client_secret' => env('UCO_CLIENT_SECRET'),
        'redirect' => env('UCO_REDIRECT_URI'),
        'scope' => ['openid', 'profile', 'email'], // Adjust scopes as needed
    ],
    
  3. First Use Case: Authentication Flow

    use League\OAuth2\Client\Provider\GenericProvider;
    use Aulasoftwarelibre\OAuth2\UCO\Provider;
    
    $provider = new Provider([
        'clientId' => config('services.uco.client_id'),
        'clientSecret' => config('services.uco.client_secret'),
        'redirectUri' => config('services.uco.redirect'),
    ]);
    
    // Generate authorization URL
    $authUrl = $provider->getAuthorizationUrl();
    return redirect()->to($authUrl);
    
    // Handle callback
    $token = $provider->getAccessToken('authorization_code', [
        'code' => request('code'),
    ]);
    $user = $provider->getResourceOwner($token);
    

Implementation Patterns

Workflows

  1. User Authentication

    • Use the provider’s getAuthorizationUrl() to redirect users to UCO’s OAuth endpoint.
    • Capture the callback with getAccessToken() and fetch user data via getResourceOwner().
    • Store the access token and refresh token securely (e.g., in the user model or session).
  2. API Integration

    • Attach the provider to Laravel’s HTTP client for authenticated requests:
      $client = new \GuzzleHttp\Client();
      $request = $client->get('https://uco.api/endpoint', [
          'auth' => [$token->getToken(), 'Bearer'],
      ]);
      
  3. Refreshing Tokens

    • Automate token refresh using Laravel’s booted event:
      use League\OAuth2\Client\Provider\Exception\TokenExpiredException;
      
      try {
          $user = $provider->getResourceOwner($token);
      } catch (TokenExpiredException $e) {
          $token = $provider->getAccessToken('refresh_token', [
              'refresh_token' => $token->getRefreshToken(),
          ]);
      }
      
  4. Laravel Integration

    • Create a custom UCOServiceProvider to wrap the OAuth flow:
      public function handleProviderCallback()
      {
          $provider = new Provider(config('services.uco'));
          $token = $provider->getAccessToken('authorization_code', request()->all());
          $user = $provider->getResourceOwner($token);
      
          // Attach user data to Laravel session/auth
          auth()->loginUsingId($user->getId());
      }
      

Gotchas and Tips

Pitfalls

  1. Scope Limitations

    • UCO’s OAuth may restrict scopes. Verify available scopes in their documentation (if available) or via trial/error.
    • Default scopes (openid, profile, email) may not cover all needs (e.g., academic data).
  2. Token Storage

    • Refresh tokens expire. Implement a job to refresh tokens before expiry:
      $token->getExpiresAt()->subMinutes(5); // Check 5 mins before expiry
      
  3. CSRF and Redirect URIs

    • Ensure redirect_uri in the provider matches exactly the callback URL registered with UCO. Mismatches cause invalid_redirect_uri errors.
  4. Error Handling

    • UCO may return custom error formats. Extend the provider:
      $provider->setHttpClient(new \GuzzleHttp\Client([
          'handler' => \Http\Message\HandlerStack::create(
              new \Aulasoftwarelibre\OAuth2\UCO\Handler\UCOErrorHandler()
          ),
      ]));
      

Tips

  1. Debugging

    • Enable Guzzle logging for OAuth requests:
      $client = new \GuzzleHttp\Client([
          'debug' => fopen('oauth_debug.log', 'w'),
      ]);
      
  2. Testing

    • Use Pest or PHPUnit to mock the provider:
      $provider = Mockery::mock(Provider::class)->makePartial();
      $provider->shouldReceive('getAuthorizationUrl')->andReturn('http://test.uco.es/auth');
      
  3. Extending User Data

    • Override getResourceOwner() to map UCO’s response to Laravel’s User model:
      $user = new User([
          'name' => $response['name'],
          'email' => $response['email'],
          'uco_id' => $response['sub'],
      ]);
      
  4. Configuration

    • Store sensitive keys in Laravel’s .env and use config('services.uco') to avoid hardcoding.
    • For multi-tenant apps, dynamically load provider configs per tenant.
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle