Weave 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

Identity Laravel Package

axium/identity

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require axium/identity
    

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

    Axium\IdentityBundle\AxiumIdentityBundle::class,
    
  2. Configuration Publish the default config:

    php artisan vendor:publish --provider="Axium\IdentityBundle\AxiumIdentityBundle" --tag="config"
    

    Update config/axium_identity.php with your OAuth2/Keycloak endpoints, client credentials, and scopes.

  3. First Use Case: Authentication Inject the AxiumIdentityClient into a controller or service:

    use Axium\IdentityBundle\Client\AxiumIdentityClient;
    
    public function __construct(private AxiumIdentityClient $identityClient) {}
    
    public function login(Request $request) {
        $token = $this->identityClient->getAccessToken($request->input('code'));
        // Store token in session or database
    }
    
  4. Key Files to Review

    • config/axium_identity.php (configuration)
    • src/Client/AxiumIdentityClient.php (core client logic)
    • src/DependencyInjection/Configuration.php (schema validation)

Implementation Patterns

Workflow: OAuth2 Flow Integration

  1. Redirect to Keycloak Generate an auth URL in a controller:

    $authUrl = $this->identityClient->getAuthorizationUrl(['openid', 'profile']);
    return redirect($authUrl);
    
  2. Callback Handling Exchange the code for a token:

    $token = $this->identityClient->getAccessToken($request->query->get('code'));
    $userInfo = $this->identityClient->getUserInfo($token);
    
  3. Token Storage Store tokens in the session or database (e.g., using Laravel's auth:attempt with a custom user provider):

    session(['access_token' => $token->getToken()]);
    session(['refresh_token' => $token->getRefreshToken()]);
    

Workflow: API Requests with Tokens

Automate token refresh and API calls:

public function fetchProtectedData() {
    $response = $this->identityClient->get('/api/protected', [
        'headers' => ['Authorization' => 'Bearer ' . session('access_token')]
    ]);
    return json_decode($response->getBody(), true);
}

Integration with Laravel Auth

Extend Laravel's User model or create a custom guard:

// config/auth.php
'guards' => [
    'keycloak' => [
        'driver' => 'session',
        'provider' => 'keycloak',
    ],
],

'providers' => [
    'keycloak' => [
        'driver' => 'custom',
        'model' => Axium\IdentityBundle\User\KeycloakUser::class,
    ],
],

Common Use Cases

  • Single Sign-On (SSO): Redirect users to Keycloak for centralized auth.
  • Token Management: Handle refresh tokens automatically.
  • User Metadata: Fetch and store user info (e.g., email, name) from /userinfo.

Gotchas and Tips

Pitfalls

  1. Token Expiry Handling

    • The bundle does not auto-refresh tokens. Implement middleware to check expiry:
      public function handle($request, Closure $next) {
          if (session('access_token_expires_at') < time()) {
              $token = $this->identityClient->refreshToken(session('refresh_token'));
              session(['access_token' => $token->getToken()]);
          }
          return $next($request);
      }
      
  2. CSRF in OAuth2 Redirects

    • Keycloak may reject requests with missing state or nonce. Always include them:
      $authUrl = $this->identityClient->getAuthorizationUrl(['openid'], [
          'state' => bin2hex(random_bytes(32)),
          'nonce' => bin2hex(random_bytes(32)),
      ]);
      
  3. Configuration Overrides

    • Avoid hardcoding credentials. Use environment variables or Laravel's .env:
      // .env
      KEYCLOAK_CLIENT_ID=your_client_id
      KEYCLOAK_CLIENT_SECRET=your_secret
      
  4. CORS Issues

    • If using Keycloak as a proxy, ensure CORS headers are configured in Keycloak's theme or client-scopes.

Debugging Tips

  • Enable Verbose Logging Add to config/axium_identity.php:

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

    Logs will appear in storage/logs/laravel.log.

  • Validate Token Responses Use dd($token->getArrayCopy()) to inspect token payloads for errors.

  • Keycloak Admin Console Check /admin in Keycloak for client events, errors, or token revocations.

Extension Points

  1. Custom Token Storage Override AxiumIdentityClient to save tokens to a database:

    class CustomIdentityClient extends AxiumIdentityClient {
        public function storeToken(Token $token) {
            TokenModel::create([
                'access_token' => $token->getToken(),
                'refresh_token' => $token->getRefreshToken(),
                'expires_at' => $token->getExpiresAt(),
            ]);
        }
    }
    
  2. Add Scopes Dynamically Extend the client to fetch available scopes from Keycloak:

    public function getAvailableScopes() {
        $response = $this->get('/protocol/openid-connect/scopes');
        return json_decode($response->getBody(), true);
    }
    
  3. Laravel Events Dispatch events for token refreshes or user info updates:

    event(new TokenRefreshed($token));
    
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.
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator