Skip to content
PHP Logo

How can PHP be integrated with a Single Sign-On server to enable seamless authentication and authorization for users accessing different domains within a system?

To integrate PHP with a Single Sign-On server for seamless authentication and authorization across different domains, you can use protocols like OAuth or SAML. These protocols allow the Single Sign-On server to handle user authentication and provide tokens or assertions that can be used by PHP applications to verify the user's identity. By implementing this integration, users can access different domains within the system without needing to log in multiple times.

php
// Example PHP code snippet using OAuth for Single Sign-On integration

// Step 1: Redirect user to Single Sign-On server for authentication
$authorizationUrl = 'https://sso-server.com/oauth/authorize';
$clientId = 'your_client_id';
$redirectUri = 'https://your-app.com/callback';
$scope = 'openid profile email';
$state = 'random_state_string';

header('Location: ' . $authorizationUrl . '?client_id=' . $clientId . '&redirect_uri=' . $redirectUri . '&scope=' . $scope . '&state=' . $state);
exit;

// Step 2: Handle callback from Single Sign-On server
if (isset($_GET['code'])) {
    $tokenUrl = 'https://sso-server.com/oauth/token';
    $tokenParams = [
        'grant_type' => 'authorization_code',
        'code' => $_GET['code'],
        'redirect_uri' => $redirectUri,
        'client_id' => $clientId,
        'client_secret' => 'your_client_secret'
    ];

    $ch = curl_init($tokenUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($tokenParams));

    $response = curl_exec($ch);
    curl_close($ch);

    $accessToken = json_decode($response)->access_token;

    // Step 3: Use access token to make authenticated requests to protected resources
    $apiUrl = 'https://api.your-app.com/user';
    $headers = [
        'Authorization: Bearer ' . $accessToken
    ];

    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $userData = curl_exec($ch);
    curl_close($ch);

    // Process user data as needed
    var_dump(json_decode($userData));
}