PHP code example of rinvex / laravel-oauth

1. Go to this page and download the library: Download rinvex/laravel-oauth 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/ */

    

rinvex / laravel-oauth example snippets


    namespace App\Models;

    use Rinvex\Oauth\Traits\HasApiTokens;
    use Illuminate\Foundation\Auth\User as Authenticatable;

    class User extends Authenticatable
    {
        use HasApiTokens;
    }
    

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    
        'api' => [
            'driver' => 'oauth',
            'provider' => 'users',
        ],
    ],
    

use Rinvex\Oauth\Models\Client as BaseClient;

class Client extends BaseClient
{
    // ...
}

'models' => [
    'client' => \Rinvex\Oauth\Models\Client::class,
    'auth_code' => \Rinvex\Oauth\Models\AuthCode::class,
    'access_token' => \Rinvex\Oauth\Models\AccessToken::class,
    'refresh_token' => \Rinvex\Oauth\Models\RefreshToken::class,
],

use Illuminate\Http\Request;
use Illuminate\Support\Str;

Route::middleware(['web'])->get('oauth/redirect', function (Request $request) {
    $request->session()->put('state', $state = Str::random(40));
    $query = http_build_query([
        'client_id' => 'client-id',
        'redirect_uri' => 'http://third-party-client-app.com/callback',
        'response_type' => 'code',
        'scope' => 'scope-id-1 scope-id-2',
        'state' => $state,
    ]);

    return redirect('http://oauth-server-app.com/oauth/authorize?'.$query);
});

use Rinvex\Oauth\Models\Client as BaseClient;

class Client extends BaseClient
{
    /**
     * Determine if the client should skip the authorization prompt.
     *
     * @return bool
     */
    public function skipsAuthorization()
    {
        return $this->firstParty();
    }
}

use Illuminate\Http\Request;
use InvalidArgumentException;
use Illuminate\Support\Facades\Http;

Route::middleware(['web'])->get('oauth/callback', function (Request $request) {
    $state = $request->session()->pull('state');

    throw_unless(
        strlen($state) > 0 && $state === $request->state,
        InvalidArgumentException::class
    );

    $response = Http::asForm()->post('http://oauth-server-app.com/oauth/token', [
        'grant_type' => 'authorization_code',
        'client_id' => 'client-id',
        'client_secret' => 'client-secret',
        'redirect_uri' => 'http://third-party-client-app.com/oauth/callback',
        'code' => $request->code,
    ]);

    return $response->json();
});

use Illuminate\Support\Facades\Http;

$response = Http::asForm()->post('http://oauth-server-app.com/oauth/token', [
    'grant_type' => 'refresh_token',
    'refresh_token' => 'the-refresh-token',
    'client_id' => 'client-id',
    'client_secret' => 'client-secret',
    'scope' => 'scope-id-1 scope-id-2',
]);

return $response->json();

app('rinvex.oauth.access_token')->where('identifier', $tokenId)->get()->revoke();

use Rinvex\Oauth\Repositories\AccessTokenRepository;
use Rinvex\Oauth\Repositories\RefreshTokenRepository;

// Revoke an access token...
$accessTokenRepository = app(AccessTokenRepository::class);
$accessTokenRepository->revokeAccessToken($tokenId);

app('rinvex.oauth.refresh_token')->where('identifier', $tokenId)->get()->revoke();

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
    $schedule->command('rinvex:oauth:purge')->hourly();
}

$encoded = base64_encode(hash('sha256', $code_verifier, true));

$codeChallenge = strtr(rtrim($encoded, '='), '+/', '-_');

use Illuminate\Support\Str;
use Illuminate\Http\Request;

Route::get('oauth/redirect', function (Request $request) {
    $request->session()->put('state', $state = Str::random(40));

    $request->session()->put(
        'code_verifier', $code_verifier = Str::random(128)
    );

    $codeChallenge = strtr(rtrim(
        base64_encode(hash('sha256', $code_verifier, true))
    , '='), '+/', '-_');

    $query = http_build_query([
        'client_id' => 'client-id',
        'redirect_uri' => 'http://third-party-app.com/callback',
        'response_type' => 'code',
        'scope' => 'scope-id-1 scope-id-2',
        'state' => $state,
        'code_challenge' => $codeChallenge,
        'code_challenge_method' => 'S256',
    ]);

    return redirect('http://oauth-server-app.com/oauth/authorize?'.$query);
});

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

Route::get('callback', function (Request $request) {
    $state = $request->session()->pull('state');

    $codeVerifier = $request->session()->pull('code_verifier');

    throw_unless(
        strlen($state) > 0 && $state === $request->state,
        InvalidArgumentException::class
    );

    $response = Http::asForm()->post('http://oauth-server-app.com/oauth/token', [
        'grant_type' => 'authorization_code',
        'client_id' => 'client-id',
        'redirect_uri' => 'http://third-party-app.com/callback',
        'code_verifier' => $codeVerifier,
        'code' => $request->code,
    ]);

    return $response->json();
});

use Illuminate\Support\Facades\Http;

$response = Http::asForm()->post('http://oauth-server-app.com/oauth/token', [
    'grant_type' => 'password',
    'client_id' => 'client-id',
    'client_secret' => 'client-secret',
    'username' => '[email protected]',
    'password' => 'my-password',
    'scope' => 'scope-id-1 scope-id-2',
]);

return $response->json();

use Illuminate\Support\Facades\Http;

$response = Http::asForm()->post('http://oauth-server-app.com/oauth/token', [
    'grant_type' => 'password',
    'client_id' => 'client-id',
    'client_secret' => 'client-secret',
    'username' => '[email protected]',
    'password' => 'my-password',
    'scope' => '*',
]);

namespace App\Models;

use Rinvex\Oauth\Traits\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * Find the user instance for the given username.
     *
     * @param  string  $username
     * @return \App\Models\User
     */
    public function findForOAuth($username)
    {
        return $this->where('username', $username)->first();
    }
}

namespace App\Models;

use Illuminate\Support\Facades\Hash;
use Rinvex\Oauth\Traits\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * Validate the password of the user for the OAuth password grant.
     *
     * @param  string  $password
     * @return bool
     */
    public function validateForOAuthPasswordGrant($password)
    {
        return Hash::check($password, $this->password);
    }
}

'grants' => [
    'Password' => ['enabled' => true, 'expire_in' => new DateInterval('P1Y')],
    'Implicit' => ['enabled' => false, 'expire_in' => new DateInterval('P1Y')],
    'AuthCode' => ['enabled' => true, 'expire_in' => new DateInterval('P1Y')],
    'RefreshToken' => ['enabled' => true, 'expire_in' => new DateInterval('P1Y')],
    'PersonalAccess' => ['enabled' => true, 'expire_in' => new DateInterval('P1Y')],
    'ClientCredentials' => ['enabled' => true, 'expire_in' => new DateInterval('P1Y')],
],

use Illuminate\Http\Request;

Route::get('redirect', function (Request $request) {
    $request->session()->put('state', $state = Str::random(40));

    $query = http_build_query([
        'client_id' => 'client-id',
        'redirect_uri' => 'http://third-party-app.com/callback',
        'response_type' => 'token',
        'scope' => 'scope-id-1 scope-id-2',
        'state' => $state,
    ]);

    return redirect('http://oauth-server-app.com/oauth/authorize?'.$query);
});

use Rinvex\Oauth\Http\Middleware\CheckClientCredentials;

protected $routeMiddleware = [
    'client' => CheckClientCredentials::class,
];

Route::get('orders', function (Request $request) {
    ...
})->middleware('client');

Route::get('/orders', function (Request $request) {
    // ...
})->middleware('client:scope-id-1,scope-id-2');

use Illuminate\Support\Facades\Http;

$response = Http::asForm()->post('http://oauth-server-app.com/oauth/token', [
    'grant_type' => 'client_credentials',
    'client_id' => 'client-id',
    'client_secret' => 'client-secret',
    'scope' => 'your-scope',
]);

return $response->json()['access_token'];

'personal_access_client' => [
    'id' => env('OAUTH_PERSONAL_ACCESS_CLIENT_ID'),
    'secret' => env('OAUTH_PERSONAL_ACCESS_CLIENT_SECRET'),
],

use App\Models\User;

$user = User::find(1);

// Creating a token without scopes...
$token = $user->createToken('Token Name')->accessToken;

// Creating a token with scopes...
$token = $user->createToken('My Token', ['scope-id-1', 'scope-id-2'])->accessToken;

Route::get('user', function () {
    // ...
})->middleware('auth:api');

'api:member' => [
    'driver' => 'oauth',
    'provider' => 'members',
],

'api:admin' => [
    'driver' => 'oauth',
    'provider' => 'admins',
],

Route::get('customer', function () {
    //
})->middleware('auth:api:member');

use Illuminate\Support\Facades\Http;

$response = Http::withHeaders([
    'Accept' => 'application/json',
    'Authorization' => 'Bearer '.$accessToken,
])->get('https://oauth-server-app.com/api/user');

return $response->json();

'default_scope' => null,

Route::get('redirect', function () {
    $query = http_build_query([
        'client_id' => 'client-id',
        'redirect_uri' => 'http://third-party-client-app.com/oauth/callback',
        'response_type' => 'code',
        'scope' => 'scope-id-1 scope-id-2',
    ]);

    return redirect('http://oauth-server-app.com/oauth/authorize?'.$query);
});

$token = $user->createToken('My Token', ['scope-id-1', 'scope-id-2'])->accessToken;

'scopes' => \Rinvex\Oauth\Http\Middleware\CheckScopes::class,
'scope' => \Rinvex\Oauth\Http\Middleware\CheckForAnyScope::class,

Route::get('orders', function () {
    // Access token has both "scope-id-2" and "scope-id-1" scopes...
})->middleware(['auth:api', 'scopes:scope-id-2,scope-id-1']);

Route::get('orders', function () {
    // Access token has either "scope-id-2" or "scope-id-1" scope...
})->middleware(['auth:api', 'scope:scope-id-2,scope-id-1']);

use Illuminate\Http\Request;

Route::get('orders', function (Request $request) {
    $scope = 'scope-id-1';

    if ($request->user()->token()->abilities->map->getRouteKey()->contains($scope)) {
        //
    }
});

'web' => [
    // Other middleware...
    \Rinvex\Oauth\Http\Middleware\CreateFreshApiToken::class,
],

'default_scope' => null,
shell
    php artisan rinvex:migrate:oauth
    
shell
php artisan rinvex:oauth:keys
shell
php artisan rinvex:publish:oauth --resource=config
shell
php artisan rinvex:oauth:client
shell
php artisan cortex:publish:oauth --resource=views
shell
php artisan rinvex:oauth:client --public
shell
php artisan rinvex:oauth:client --password
shell
php artisan rinvex:oauth:client --client_credentials
shell
php artisan rinvex:oauth:client --personal_access
shell
php artisan rinvex:publish:oauth --resource=config