Magium\ActiveDirectory:无需手动Graph调用获取用户所属组的咨询
问题:使用Magium Active Directory库获取用户所属组
我尝试使用Magium的Active Directory库(用于Azure AD)来列出用户被分配的组,已经配置并授权了Group.Read.All权限。以下是我的代码实现:
function test() { session_start(); $config = [ 'authentication' => [ 'ad' => [ 'client_id' => '', 'client_secret' => '', 'return_url' => '', 'enabled' => '', 'directory' => '' ] ] ]; $request = new \Zend\Http\PhpEnvironment\Request(); $ad = new \Magium\ActiveDirectory\ActiveDirectory( new \Magium\Configuration\Config\Repository\ArrayConfigurationRepository($config), Zend\Psr7Bridge\Psr7ServerRequest::fromZend(new \Zend\Http\PhpEnvironment\Request()), null, null, "profile openid email offline_access User.Read Group.Read.All " ); try { $entity = $ad->authenticate(); echo $entity->getName() . '<Br />'; echo $entity->getOid() . '<Br />'; echo $entity->getPreferredUsername() . '<Br />'; echo "<pre>"; print_r($entity); echo "</pre>"; } catch(Magium\ActiveDirectory\InvalidRequestException $e) { echo "<pre>"; print_r($e); echo "</pre>"; } }
现咨询:是否可通过该库直接获取用户所属组,无需手动调用Graph API?望得到相关技术指导。
解答
首先明确一点:Magium Active Directory库的核心定位是处理Azure AD的身份验证流程——比如OAuth2/OpenID Connect授权、token获取、用户身份信息解析这些基础工作,它本身并没有内置直接获取用户所属组的方法。
不过你已经完成了最关键的步骤:成功获取了认证后的$entity对象,并且已经授权了Group.Read.All权限。接下来你可以利用这个对象里的有效access token,直接调用Microsoft Graph API来获取用户组信息,这是最合规高效的方式。
给你一个在现有代码基础上扩展的示例:
function test() { session_start(); $config = [ 'authentication' => [ 'ad' => [ 'client_id' => '', 'client_secret' => '', 'return_url' => '', 'enabled' => '', 'directory' => '' ] ] ]; $request = new \Zend\Http\PhpEnvironment\Request(); $ad = new \Magium\ActiveDirectory\ActiveDirectory( new \Magium\Configuration\Config\Repository\ArrayConfigurationRepository($config), Zend\Psr7Bridge\Psr7ServerRequest::fromZend(new \Zend\Http\PhpEnvironment\Request()), null, null, "profile openid email offline_access User.Read Group.Read.All " ); try { $entity = $ad->authenticate(); // 原有输出代码 echo $entity->getName() . '<Br />'; echo $entity->getOid() . '<Br />'; echo $entity->getPreferredUsername() . '<Br />'; echo "<pre>用户基础信息:</pre>"; print_r($entity); echo "</pre>"; // 获取access token并调用Graph API $accessToken = $entity->getAccessToken(); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://graph.microsoft.com/v1.0/me/memberOf'); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer ' . $accessToken, 'Content-Type: application/json' ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); $groups = json_decode($response, true); echo "<h3>用户所属组:</h3>"; echo "<pre>"; print_r($groups); echo "</pre>"; } catch(Magium\ActiveDirectory\InvalidRequestException $e) { echo "<pre>"; print_r($e); echo "</pre>"; } }
如果你想让代码更优雅,也可以引入Microsoft官方的Graph SDK for PHP,但对于简单的组查询需求,上面的curl实现已经足够满足需求。
总结:这个库本身没有直接获取组的封装,但它帮你搞定了最繁琐的身份验证和token管理,剩下的只需要用拿到的access token调用Graph API即可,完全不需要额外的授权操作。
内容的提问来源于stack exchange,提问作者Dev
相关产品推荐
相关产品推荐

