BxAzrB2CModule.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup AzureB2CConnect Azure B2C Connect
  7. * @ingroup UnaModules
  8. *
  9. * @{
  10. */
  11. $aPathInfo = pathinfo(__FILE__);
  12. require_once ($aPathInfo['dirname'] . '/../vendor/autoload.php');
  13. use Alancting\Microsoft\JWT\AzureAd\AzureAdConfiguration;
  14. use Alancting\Microsoft\JWT\AzureAd\AzureAdAccessTokenJWT;
  15. use Alancting\Microsoft\JWT\AzureAd\AzureAdIdTokenJWT;
  16. /**
  17. * This Azude AD connect code was created with instructions from:
  18. * https://www.sipponen.com/archives/4024
  19. */
  20. class BxAzrB2CModule extends BxBaseModConnectModule
  21. {
  22. function __construct(&$aModule)
  23. {
  24. parent::__construct($aModule);
  25. }
  26. /**
  27. * Redirect to remote site login form
  28. *
  29. * @return n/a - redirect or HTML page in case of error
  30. */
  31. function actionStart()
  32. {
  33. if (isset($_GET["error"])) {
  34. $this->_oTemplate->getPage(_t($this->_oConfig->sDefaultTitleLangKey), DesignBoxContent(_t($this->_oConfig->sDefaultTitleLangKey), MsgBox(bx_get('error'))));
  35. exit;
  36. }
  37. if (isLogged()) {
  38. $this->_redirect ($this -> _oConfig -> sDefaultRedirectUrl);
  39. }
  40. if (!$this->_oConfig->sClientID || !$this->_oConfig->sSecret) {
  41. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  42. bx_import('BxDolLanguages');
  43. $sCode = MsgBox( _t('_bx_azrb2c_profile_error_api_keys') );
  44. $this->_oTemplate->getPage(_t('_bx_azrb2c'), $sCode);
  45. }
  46. else {
  47. // First stage of the authentication process; This is just a simple redirect (first load of this page)
  48. $verifier_bytes = random_bytes(64);
  49. $code_verifier = rtrim(strtr(base64_encode($verifier_bytes), "+/", "-_"), "=");
  50. BxDolSession::getInstance()->setValue('code_verifier', $code_verifier);
  51. $challenge_bytes = hash("sha256", $code_verifier, true);
  52. $code_challenge = rtrim(strtr(base64_encode($challenge_bytes), "+/", "-_"), "=");
  53. $sBaseUrl = "https://" . $this->_oConfig->sDomain . "/" . $this->_oConfig->sTenant . "/" . $this->_oConfig->sPolicy;//B2C_1_login_una";
  54. $sUrl = bx_append_url_params($sBaseUrl . "/oauth2/v2.0/authorize", [
  55. 'state' => $this->_genToken(), // This at least semi-random string is likely good enough as state identifier
  56. 'scope' => $this->_oConfig->sScope,
  57. 'response_type' => 'code',
  58. 'response_mode' => 'query',
  59. 'prompt' => 'login',
  60. 'client_id' => $this->_oConfig->sClientID,
  61. 'redirect_uri' => $this->_oConfig->sPageHandle,
  62. 'client_info' => 1,
  63. 'code_challenge_method' => 'S256',
  64. 'code_challenge' => $code_challenge,
  65. ]);
  66. $this->_redirect($sUrl); // So off you go my dear browser and welcome back for round two after some redirects at Azure end
  67. }
  68. }
  69. function actionHandle()
  70. {
  71. require_once(BX_DIRECTORY_PATH_INC . 'design.inc.php');
  72. // check CSRF token
  73. if ($this->_getToken() != bx_get('state')) {
  74. $this->_oTemplate->getPage(_t('_Error'), MsgBox(_t('_sys_connect_state_invalid')));
  75. return;
  76. }
  77. // check code
  78. $sCode = bx_get('code');
  79. if (!$sCode || bx_get('error')) {
  80. $sErrorDescription = bx_get('error_description') ? bx_get('error_description') : _t('_error occured');
  81. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  82. return;
  83. }
  84. // Verifying the received tokens with Azure and finalizing the authentication part
  85. $sBaseUrl = "https://" . $this->_oConfig->sDomain . "/" . $this->_oConfig->sTenant . "/" . $this->_oConfig->sPolicy;
  86. $s = bx_file_get_contents($sBaseUrl . "/oauth2/v2.0/token", [
  87. 'grant_type' => 'authorization_code',
  88. 'client_id' => $this->_oConfig->sClientID,
  89. 'scope' => $this->_oConfig->sScope,
  90. 'redirect_uri' => $this->_oConfig->sPageHandle,
  91. 'code' => $sCode,
  92. 'client_secret' => $this->_oConfig->sSecret,
  93. 'code_verifier' => BxDolSession::getInstance()->getValue('code_verifier'),
  94. ], 'post', array ('Content-Type: application/x-www-form-urlencoded'));
  95. $aAuthData = $this->_decodeResponseAndHandleError($s);
  96. // get the data, especially id_token
  97. $sIdToken = $aAuthData['id_token'];
  98. // parse token to get the data
  99. //
  100. // to make library to with B2C correctly please comment out the following lines in
  101. // vendor/alancting/php-microsoft-jwt/src/Base/MicrosoftConfiguration.php
  102. // file near ~240 line
  103. // @code
  104. // !array_key_exists('userinfo_endpoint', $data)
  105. // !array_key_exists('device_authorization_endpoint', $data)
  106. // @endcode
  107. // then further in the code add checking for not set values for these values
  108. $aConfigOptions = [
  109. 'tenant' => $this->_oConfig->sTenantID,
  110. 'tenant_id' => $this->_oConfig->sTenantID,
  111. 'client_id' => $this->_oConfig->sClientID,
  112. 'config_uri' => "https://" . $this->_oConfig->sDomain . "/" . $this->_oConfig->sTenant . "/" . $this->_oConfig->sPolicy . "/v2.0/.well-known/openid-configuration",
  113. ];
  114. $oConfig = new AzureAdConfiguration($aConfigOptions);
  115. $oIdTokenJWT = new AzureAdIdTokenJWT($oConfig, $sIdToken);
  116. $aUserData = [
  117. 'id' => $oIdTokenJWT->get('oid'),
  118. 'name' => $oIdTokenJWT->get('given_name'),
  119. 'last_name' => $oIdTokenJWT->get('family_name'),
  120. 'email' => reset($oIdTokenJWT->get('emails')),
  121. ];
  122. $aRemoteProfileInfo = $aUserData;
  123. if ($aRemoteProfileInfo) {
  124. // check if user logged in before
  125. $iLocalProfileId = $this->_oDb->getProfileId($aRemoteProfileInfo['id']);
  126. if ($iLocalProfileId && $oProfile = BxDolProfile::getInstance($iLocalProfileId)) {
  127. // user already exists
  128. $this->setLogged($oProfile ->id());
  129. }
  130. else {
  131. // register new user
  132. $this->_createProfile($aRemoteProfileInfo);
  133. }
  134. }
  135. else {
  136. $this->_oTemplate->getPage(_t('_Error'), MsgBox(_t('_sys_connect_profile_error_info')));
  137. }
  138. }
  139. /**
  140. * @param $aProfileInfo - remote profile info
  141. * @param $sAlternativeName - suffix to add to NickName to make it unique
  142. * @return profile array info, ready for the local database
  143. */
  144. protected function _convertRemoteFields($aProfileInfo, $sAlternativeName = '')
  145. {
  146. $aProfileFields = $aProfileInfo;
  147. $aProfileFields['fullname'] = !empty($aProfileInfo['last_name']) ? $aProfileInfo['name'] . ' ' . $aProfileInfo['last_name'] : $aProfileFields['name'];
  148. $aProfileFields['picture'] = ''; // isset($aProfileInfo['picture']) ? $aProfileInfo['picture'] : '';
  149. $aProfileFields['allow_view_to'] = getParam('bx_azrb2c_privacy');
  150. return $aProfileFields;
  151. }
  152. protected function _decodeResponseAndHandleError($s, $bDisplayErrorPage = true)
  153. {
  154. if (!$s || NULL === ($aData = json_decode($s, true)) || !$aData || isset($aData['error'])) {
  155. if (is_array($aData['error']) && !empty($aData['error']['message']))
  156. $sErrorDescription = $aData['error']['message'];
  157. else
  158. $sErrorDescription = isset($aData['error_description']) ? $aData['error_description'] : _t('_error occured');
  159. if ($bDisplayErrorPage) {
  160. $this->_oTemplate->getPage(_t('_Error'), MsgBox($sErrorDescription));
  161. exit;
  162. }
  163. else {
  164. return false;
  165. }
  166. }
  167. return $aData;
  168. }
  169. }
  170. /** @} */