PHP code example of notrel / laravel-wso2is

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

    

notrel / laravel-wso2is example snippets


'wso2is' => [
    'base_url' => env('WSO2IS_BASE_URL', 'https://localhost:9443'),
    'client_id' => env('WSO2IS_CLIENT_ID'),
    'client_secret' => env('WSO2IS_CLIENT_SECRET'),
    'redirect_uri' => env('WSO2IS_REDIRECT_URI'),
    'scopes' => env('WSO2IS_SCOPES', 'openid,profile,email'),
    'scim_username' => env('WSO2IS_SCIM_USERNAME'),
    'scim_password' => env('WSO2IS_SCIM_PASSWORD'),
],

// routes/web.php
use Notrel\LaravelWso2is\Http\Requests\Wso2isLoginRequest;
use Notrel\LaravelWso2is\Http\Requests\Wso2isAuthenticationRequest;
use Notrel\LaravelWso2is\Http\Requests\Wso2isLogoutRequest;
use Notrel\LaravelWso2is\Http\Requests\Wso2isAccountDeletionRequest;

Route::get('/auth/login', function (Wso2isLoginRequest $request) {
    return $request->redirect([
        'prompt' => 'login', // Optional: force login prompt
        'loginHint' => '[email protected]', // Optional: pre-fill username
        'domainHint' => 'example.com', // Optional: domain hint
    ]);
})->name('auth.login');

Route::get('/auth/callback', function (Wso2isAuthenticationRequest $request) {
    $user = $request->authenticate();
    return $request->redirect('/dashboard');
})->name('auth.callback');

Route::post('/auth/logout', function (Wso2isLogoutRequest $request) {
    return $request->logout('/'); // Optional: redirect URL after logout
})->name('auth.logout');

Route::delete('/auth/delete-account', function (Wso2isAccountDeletionRequest $request) {
    return $request->deleteAccount(redirectTo: '/'); // Optional: redirect URL after deletion
})->name('auth.delete-account')->middleware('auth');

// app/Http/Controllers/AuthController.php


namespace App\Http\Controllers;

use Notrel\LaravelWso2is\Http\Requests\Wso2isLoginRequest;
use Notrel\LaravelWso2is\Http\Requests\Wso2isAuthenticationRequest;
use Notrel\LaravelWso2is\Http\Requests\Wso2isLogoutRequest;
use Notrel\LaravelWso2is\Http\Requests\Wso2isAccountDeletionRequest;

class AuthController extends Controller
{
    public function login(Wso2isLoginRequest $request)
    {
        return $request->redirect(['prompt' => 'login']);
    }

    public function callback(Wso2isAuthenticationRequest $request)
    {
        $user = $request->authenticate(
            // Optional: custom user finder
            findUsing: fn($wso2isUser) => User::where('wso2is_id', $wso2isUser->id)->first(),
            
            // Optional: custom user creator
            createUsing: fn($wso2isUser) => User::create([
                'name' => $wso2isUser->getFullName(),
                'email' => $wso2isUser->email,
                'wso2is_id' => $wso2isUser->id,
            ]),
            
            // Optional: custom user updater
            updateUsing: fn($user, $wso2isUser) => $user->update([
                'name' => $wso2isUser->getFullName(),
            ])
        );
        
        return $request->redirect('/dashboard');
    }

    public function logout(Wso2isLogoutRequest $request)
    {
        return $request->logout('/');
    }

    public function deleteAccount(Wso2isAccountDeletionRequest $request)
    {
        return $request->deleteAccount(
            // Optional: custom user deletion
            deleteUsing: fn($user) => $user->delete(),
            redirectTo: '/'
        );
    }
}

Route::middleware('wso2is.session')->group(function () {
    Route::get('/dashboard', function () {
        // User is guaranteed to have valid WSO2IS session
        return view('dashboard');
    });
    
    Route::get('/profile', function () {
        // Access tokens are automatically refreshed if needed
        return view('profile');
    });
});

use Notrel\LaravelWso2is\Wso2is;

$user = Wso2is::getUserFromToken($accessToken);

// User properties
echo $user->id;
echo $user->email;
echo $user->getFullName();
echo $user->username;

// Role checking
if ($user->hasRole('admin')) {
    // User has admin role
}

if ($user->hasAnyRole(['admin', 'moderator'])) {
    // User has at least one of these roles
}

// Group checking
if ($user->inGroup('developers')) {
    // User is in developers group
}

if ($user->inAnyGroup(['qa', 'testers'])) {
    // User is in at least one of these groups
}

// Convert to array
$userData = $user->toArray();

use Notrel\LaravelWso2is\Http\Client;

// Create a client instance
$client = new Client(
    baseUrl: config('services.wso2is.base_url'),
    clientId: config('services.wso2is.client_id'),
    clientSecret: config('services.wso2is.client_secret')
);

// Get access token
$token = $client->getAccessToken();

// Make raw API requests
$users = $client->get('/scim2/Users');

use Notrel\LaravelWso2is\Http\Client;

// Create a client instance
$client = new Client(
    baseUrl: config('services.wso2is.base_url'),
    clientId: config('services.wso2is.client_id'),
    clientSecret: config('services.wso2is.client_secret')
);

// List all users
$users = $client->users()->list();

// Get a specific user
$user = $client->users()->get('user-id');

// Get user by username
$user = $client->users()->getByUsername('john.doe');

// Get user by email
$user = $client->users()->getByEmail('[email protected]');

// Create a new user
$newUser = $client->users()->create([
    'userName' => 'john.doe',
    'name' => [
        'givenName' => 'John',
        'familyName' => 'Doe'
    ],
    'emails' => [
        [
            'value' => '[email protected]',
            'primary' => true
        ]
    ],
    'password' => 'securePassword123'
]);

// Update a user
$updatedUser = $client->users()->update('user-id', [
    'name' => [
        'givenName' => 'John',
        'familyName' => 'Smith'
    ]
]);

// Delete a user
$client->users()->delete('user-id');

use Notrel\LaravelWso2is\Http\Client;

// Create a client instance
$client = new Client(
    baseUrl: config('services.wso2is.base_url'),
    clientId: config('services.wso2is.client_id'),
    clientSecret: config('services.wso2is.client_secret')
);

// List all groups
$groups = $client->groups()->list();

// Get a specific group
$group = $client->groups()->get('group-id');

// Get group by name
$group = $client->groups()->getByName('Administrators');

// Create a new group
$newGroup = $client->groups()->create([
    'displayName' => 'New Group',
    'members' => [
        [
            'value' => 'user-id-1',
            'display' => 'user-id-1'
        ]
    ]
]);

// Add user to group
$client->groups()->addUser('group-id', 'user-id');

// Remove user from group
$client->groups()->removeUser('group-id', 'user-id');

// Delete a group
$client->groups()->delete('group-id');

use Notrel\LaravelWso2is\Http\Client;

// Create a client instance
$client = new Client(
    baseUrl: config('services.wso2is.base_url'),
    clientId: config('services.wso2is.client_id'),
    clientSecret: config('services.wso2is.client_secret')
);

// List all applications
$applications = $client->applications()->list();

// Get a specific application
$app = $client->applications()->get('app-id');

// Get application by name
$app = $client->applications()->getByName('My App');

// Create a new application
$newApp = $client->applications()->create([
    'name' => 'My Laravel App',
    'description' => 'A Laravel application'
]);

// Get OAuth2 configuration
$oauthConfig = $client->applications()->getOAuth2Config('app-id');

// Update OAuth2 configuration
$updatedConfig = $client->applications()->updateOAuth2Config('app-id', [
    'grantTypes' => ['authorization_code', 'refresh_token'],
    'callbackURLs' => ['https://myapp.com/auth/callback']
]);

// Regenerate client secret
$newSecret = $client->applications()->regenerateClientSecret('app-id');

// In your controller
use Notrel\LaravelWso2is\Http\Requests\Wso2isLoginRequest;
use Notrel\LaravelWso2is\Http\Requests\Wso2isAuthenticationRequest;
use Notrel\LaravelWso2is\Http\Requests\Wso2isLogoutRequest;

// Initiate login
// Option 1: Direct redirect (recommended for web apps)
public function login()
{
    $loginRequest = new Wso2isLoginRequest();
    return $loginRequest->redirect();
}

// Option 2: Get URL for custom handling (useful for APIs/AJAX)
public function getLoginUrl()
{
    $loginRequest = new Wso2isLoginRequest();
    return response()->json([
        'login_url' => $loginRequest->getRedirectUrl()
    ]);
}

// Handle callback
public function callback(Request $request)
{
    $authRequest = new Wso2isAuthenticationRequest($request);
    
    try {
        $user = $authRequest->getUser();
        // Handle successful authentication
        // Store user data, create session, etc.
        
        return redirect('/dashboard');
    } catch (\Exception $e) {
        // Handle authentication error
        return redirect('/login')->withErrors(['error' => 'Authentication failed']);
    }
}

// Handle logout
public function logout()
{
    $logoutRequest = new Wso2isLogoutRequest();
    
    // Clear local session
    auth()->logout();
    session()->flush();
    
    // Option 1: Direct redirect (recommended for web apps)
    return $logoutRequest->redirect();
    
    // Option 2: Get URL for custom handling (useful for APIs/AJAX)
    // return response()->json(['logout_url' => $logoutRequest->getRedirectUrl()]);
}

$authUrl = 'https://your-wso2is-instance.com/oauth2/authorize?' . http_build_query([
    'response_type' => 'code',
    'client_id' => config('services.wso2is.client_id'),
    'redirect_uri' => route('wso2is.callback'),
    'scope' => 'openid profile email',
    'state' => csrf_token()
]);

return redirect($authUrl);