BxAzrB2CModule.php 8.7 KB

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