PHP code example of colq2 / laravel-keycloak

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

    

colq2 / laravel-keycloak example snippets




class LoginController extends \Illuminate\Routing\Controller
{
    /**
     * @var \colq2\Keycloak\Contracts\Authenticator
     */
    private $authenticator;

    public function __construct(\colq2\Keycloak\Contracts\Authenticator $authenticator)
    {

        $this->authenticator = $authenticator;
    }

    public function handleRedirect()
    {
        $this->authenticator->handleRedirect();
    }

    public function handleCallback()
    {
        $this->handleCallback();

        $user = auth()->user();
    }
}

protected $routeMiddleware = [
    // ...
    'realm_access' => \colq2\Keycloak\Http\Middleware\CheckRealmAccess::class,
    'resource_access' => \colq2\Keycloak\Http\Middleware\CheckResourceAccess::class,
];

Route::get('post/{post}', function(Post $post) {
    // The current user has role1 and role2 in the realm
})->middleware('realm_access:role1,role2');

Route::get('post/{post}', function(Post $post) {
    // The current user has role1 and role2 in client1 in the realm
})->middleware('resource_access:client1,role1,role2');



namespace colq2\Keycloak;

use colq2\Keycloak\Contracts\Roles\HasRoles;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\Authorizable;

class KeycloakUser extends Model implements AuthenticatableContract, AuthorizableContract, HasRoles
{
    use Authenticatable, Authorizable;

    protected $table = 'users';

    protected $fillable = [ 'sub', 'username', 'name', 'email', 'picture', 'roles' ];

    protected $casts = [ 'roles' => 'array' ];

    protected $hidden = [ 'remember_token' ];

    public function getAllRoles(): array
    {
        return $this->roles;
    }
}




namespace colq2\Keycloak\Examples;

use colq2\Keycloak\KeycloakUserService;

class CustomUserService extends KeycloakUserService
{

    /**
     * @param array $user
     * @return array|\colq2\Keycloak\KeycloakUser
     */
    public function mapUser(array $user): array
    {
        // Do whatever you need
        $user['username'] = $user['preferred_username'];

        // And return it
        return $user;
    }
}