PHP code example of bherila / auth-laravel

1. Go to this page and download the library: Download bherila/auth-laravel library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bherila / auth-laravel example snippets


use BWH\Auth\Http\Controllers\OAuthTokenIntrospectionController;

Route::post('/oauth/introspect', OAuthTokenIntrospectionController::class)
    ->middleware('throttle:60,1');

'oauth_server' => [
    // existing server configuration...
    'introspection' => [
        'enabled' => true,
        'clients' => [[
            'id' => env('OAUTH_INTROSPECTION_CLIENT_ID'),
            // Store only password_hash($secret, PASSWORD_DEFAULT) here.
            'secret_hash' => env('OAUTH_INTROSPECTION_CLIENT_SECRET_HASH'),
            'resource' => 'https://resource.example.test/mcp',
        ]],
    ],
],

use BWH\Auth\OAuth\Introspection\OAuthTokenIntrospector;

$token = app(OAuthTokenIntrospector::class)->introspect($request->bearerToken() ?? '');

public function canLogin(Authenticatable $user, Request $request): bool;

public function canLogin(Authenticatable $user, Request $request): bool
{
    return $user instanceof User && $user->canLogin() && $user->hasVerifiedEmail();
}

use BWH\Auth\Services\TwoFactorService;

$attempt = app(TwoFactorService::class)->startChallenge(
    $user,
    $request,
    $request->boolean('remember'),
);

return response()->json([
    'success' => true,
    '

'oauth_server' => [
    'enabled' => true,
    'issuer' => 'https://example.test',
    'resource' => 'https://example.test/mcp',
    'protected_resource_metadata_url' =>
        'https://example.test/.well-known/oauth-protected-resource/mcp',
    'scopes' => [
        'mcp:use' => 'Connect through MCP',
    ],
'resource_

Passport::tokensCan(config('bherila-auth.oauth_server.scopes', []));

public function redirect(Request $request, OAuthClient $oauth): RedirectResponse
{
    return $oauth->redirect($request);
}

public function callback(Request $request, OAuthClient $oauth): RedirectResponse
{
    $identity = $oauth->identityFromCallback($request);
    $user = $this->resolveLocalUser($identity);

    Auth::login($user);
    $request->session()->regenerate();

    return redirect()->intended('/');
}

class OAuthLoginController extends Controller
{
    use SignsOutThroughProvider;

    public function logout(Request $request, OAuthClient $oauth): RedirectResponse
    {
        return $this->signOutThroughProvider($request, $oauth);
    }

    // Optional; a no-op unless the application keeps an audit trail.
    protected function afterLocalSignOut(Request $request, ?Authenticatable $user): void
    {
        $this->auditLoggedOut($request, $user);
    }
}

ProviderApplications::remember($request, $identity->apps);   // in callback()
ProviderApplications::forRequest($request);                  // in Blade, Inertia, a view composer

// app/Auth/AppUserPolicy.php
class AppUserPolicy extends DefaultAuthUserPolicy
{
    public function canLogin(Authenticatable $user, Request $request): bool
    {
        return $user->approved_at !== null
            && ! $user->is_disabled;
    }
}

// AppServiceProvider::register()
$this->app->bind(AuthUserPolicy::class, AppUserPolicy::class);

// AppServiceProvider::boot()
Gate::define('admin-only', function (User $user) {
    // WRONG: only checks role — a pending admin bypasses account-state checks
    // return $user->is_admin;

    // CORRECT: role AND account state
    return $user->is_admin
        && $user->approved_at !== null
        && ! $user->is_disabled;
});

// In your migration's up() method, after adding the column:
DB::table('users')
    ->whereNull('approved_at')
    ->update(['approved_at' => now()]);

use BWH\Auth\Concerns\LogsAuthEvents;

class LoginController
{
    use LogsAuthEvents;

    public function login(Request $request)
    {
        // ... resolve $user, attempt credentials ...
        if (! $ok) {
            $this->auditLoginFailed($request, $user, $request->input('email'), 'Invalid credentials');
            // ...
        }

        $this->auditLoginSucceeded($request, $user); // method defaults to 'password'
    }

    public function logout(Request $request)
    {
        $this->auditLoggedOut($request, $request->user());
        // ...
    }
}

// bootstrap/app.php or a scheduler
$schedule->command('bherila-auth:prune-audit-log')->daily();

Schedule::command('model:prune', ['--model' => [\BWH\Auth\Models\AuthAuditLog::class]])->daily();

use BWH\Auth\Concerns\LogsAuthEvents;
use BWH\Auth\Concerns\ThrottlesLoginAttempts;

class LoginController
{
    use LogsAuthEvents;
    use ThrottlesLoginAttempts;

    public function login(Request $request)
    {
        $email = $request->input('email');
        $state = $this->inspectLoginThrottle($request, null, $email);

        if ($state->locked) {
            $this->auditLoginBlocked($request, null, $email, 'password', $state);

            return response()->json([
                'message' => 'Too many login attempts.',
                'retry_after' => $state->availableInSeconds(),
            ], 429);
        }

        // ... attempt credentials ...
        if (! $ok) {
            $this->auditLoginFailed($request, $user, $email, 'Invalid credentials');
            // ...
        }

        $this->auditLoginSucceeded($request, $user);
    }
}

use BWH\Auth\OAuth\DelegatedAccess\ActorAssertionVerifier;
use BWH\Auth\OAuth\DelegatedAccess\DatabaseNonceStore;

$verifier = new ActorAssertionVerifier(
    issuer: 'https://identity.example.test',
    endpoint: 'https://application.example.test/application-access',
    application: 'example-app',
    publicKeys: ['integration-v1' => $pinnedPublicKeyPem],
    nonces: new DatabaseNonceStore($dedicatedNonceDatabaseConnection),
);
$actorSubject = $verifier->verify($assertion, $request->method(), $request->getContent());

   $this->app->bind(ApplicationAccessAdapter::class, MyApplicationAccessAdapter::class);
   
sh
php artisan vendor:publish --tag=bherila-auth-migrations
php artisan migrate
sh
composer n vendor:publish --tag=bherila-auth-config
php artisan vendor:publish --tag=bherila-auth-migrations
php artisan migrate
sh
php artisan vendor:publish --tag=bherila-auth-views
sh
php artisan vendor:publish --tag=bherila-auth-config
php artisan vendor:publish --tag=bherila-auth-migrations
php artisan migrate
bash
php artisan bherila-auth:prune-audit-log
sh
php artisan vendor:publish --tag=bherila-auth-delegated-access-migrations