Skip to content

EspoCRM – Open Source CRM Application

OAuth providers PKCE

Yurii1a4f114967ec
diff --git a/application/Espo/Entities/OAuthProvider.php b/application/Espo/Entities/OAuthProvider.php
index fa5ce8c951..6c4bf541a9 100644
--- a/application/Espo/Entities/OAuthProvider.php
+++ b/application/Espo/Entities/OAuthProvider.php
@@ -110,4 +110,9 @@ class OAuthProvider extends Entity
{
return $this->get('authorizationParams') ?? null;
}
+
+ public function useAuthorizationPkce(): bool
+ {
+ return $this->get('authorizationPkce') ?? false;
+ }
}
diff --git a/application/Espo/Resources/i18n/en_US/OAuthProvider.json b/application/Espo/Resources/i18n/en_US/OAuthProvider.json
index 9bec51ecc6..7368ef5a18 100644
--- a/application/Espo/Resources/i18n/en_US/OAuthProvider.json
+++ b/application/Espo/Resources/i18n/en_US/OAuthProvider.json
@@ -13,7 +13,8 @@
"scopeSeparator": "Scope Separator",
"hasAccessToken": "Has Access Token",
"authorizationPrompt": "Authorization Prompt",
- "authorizationParams": "Authorization Params"
+ "authorizationParams": "Authorization Params",
+ "authorizationPkce": "Use PKCE"
},
"links": {
"accounts": "Accounts"
diff --git a/application/Espo/Resources/layouts/OAuthProvider/detail.json b/application/Espo/Resources/layouts/OAuthProvider/detail.json
index 4c6ff5a994..075f4676a6 100644
--- a/application/Espo/Resources/layouts/OAuthProvider/detail.json
+++ b/application/Espo/Resources/layouts/OAuthProvider/detail.json
@@ -15,7 +15,8 @@
"rows": [
[{"name": "scopes"}],
[{"name": "scopeSeparator"}, false],
- [{"name": "authorizationParams"}, {"name": "authorizationPrompt"}]
+ [{"name": "authorizationParams"}, {"name": "authorizationPrompt"}],
+ [{"name": "authorizationPkce"}, false]
]
},
{
diff --git a/application/Espo/Resources/metadata/entityDefs/OAuthAccount.json b/application/Espo/Resources/metadata/entityDefs/OAuthAccount.json
index f76a38b452..2f39a8d15c 100644
--- a/application/Espo/Resources/metadata/entityDefs/OAuthAccount.json
+++ b/application/Espo/Resources/metadata/entityDefs/OAuthAccount.json
@@ -29,12 +29,6 @@
"link": "provider",
"field": "isActive"
},
- "data": {
- "type": "jsonObject",
- "notStorable": true,
- "directAccessDisabled": true,
- "readOnly": true
- },
"accessToken": {
"type": "password",
"readOnly": true,
diff --git a/application/Espo/Resources/metadata/entityDefs/OAuthProvider.json b/application/Espo/Resources/metadata/entityDefs/OAuthProvider.json
index 08a69fd338..445725a63f 100644
--- a/application/Espo/Resources/metadata/entityDefs/OAuthProvider.json
+++ b/application/Espo/Resources/metadata/entityDefs/OAuthProvider.json
@@ -22,13 +22,15 @@
"type": "url",
"maxLength": 512,
"dbType": "text",
- "strip": false
+ "strip": false,
+ "protocolRequired": true
},
"tokenEndpoint": {
"type": "url",
"maxLength": 512,
"dbType": "text",
- "strip": false
+ "strip": false,
+ "protocolRequired": true
},
"authorizationRedirectUri": {
"type": "url",
@@ -48,6 +50,9 @@
],
"maxLength": 14
},
+ "authorizationPkce": {
+ "type": "bool"
+ },
"scopes": {
"type": "array",
"noEmptyString": true,
diff --git a/application/Espo/Resources/metadata/recordDefs/OAuthAccount.json b/application/Espo/Resources/metadata/recordDefs/OAuthAccount.json
index 4b34b8783f..0967ef424b 100644
--- a/application/Espo/Resources/metadata/recordDefs/OAuthAccount.json
+++ b/application/Espo/Resources/metadata/recordDefs/OAuthAccount.json
@@ -1,5 +1 @@
-{
- "readLoaderClassNameList": [
- "Espo\\Classes\\FieldProcessing\\OAuthAccount\\DataLoader"
- ]
-}
+{}
diff --git a/application/Espo/Resources/routes.json b/application/Espo/Resources/routes.json
index fcd9f95c2a..04d2e02515 100644
--- a/application/Espo/Resources/routes.json
+++ b/application/Espo/Resources/routes.json
@@ -536,6 +536,11 @@
"route": "/OAuth/:id/connection",
"actionClassName": "Espo\\Tools\\OAuth\\Api\\DeleteConnection"
},
+ {
+ "method": "get",
+ "route": "/OAuth/:id/authorizationData",
+ "actionClassName": "Espo\\Tools\\OAuth\\Api\\GetAuthorizationData"
+ },
{
"method": "get",
"route": "/OpenApi",
diff --git a/application/Espo/Classes/FieldProcessing/OAuthAccount/DataLoader.php b/application/Espo/Tools/OAuth/Api/GetAuthorizationData.php
similarity index 57%
rename from application/Espo/Classes/FieldProcessing/OAuthAccount/DataLoader.php
rename to application/Espo/Tools/OAuth/Api/GetAuthorizationData.php
index 6493a14ef8..d2463b26c6 100644
--- a/application/Espo/Classes/FieldProcessing/OAuthAccount/DataLoader.php
+++ b/application/Espo/Tools/OAuth/Api/GetAuthorizationData.php
@@ -27,46 +27,35 @@
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
-namespace Espo\Classes\FieldProcessing\OAuthAccount;
-
-use Espo\Core\FieldProcessing\Loader;
-use Espo\Core\FieldProcessing\Loader\Params;
+namespace Espo\Tools\OAuth\Api;
+
+use Espo\Core\Api\Action;
+use Espo\Core\Api\Request;
+use Espo\Core\Api\Response;
+use Espo\Core\Api\ResponseComposer;
+use Espo\Core\Exceptions\BadRequest;
+use Espo\Core\Record\EntityProvider;
use Espo\Entities\OAuthAccount;
-use Espo\ORM\Entity;
-use Espo\Tools\OAuth\ConfigDataProvider;
+use Espo\Tools\OAuth\ConnectionService;
/**
- * @implements Loader<OAuthAccount>
+ * @noinspection PhpUnused
*/
-class DataLoader implements Loader
+class GetAuthorizationData implements Action
{
public function __construct(
- private ConfigDataProvider $configDataProvider,
+ private ConnectionService $service,
+ private EntityProvider $entityProvider,
) {}
- public function process(Entity $entity, Params $params): void
+ public function process(Request $request): Response
{
- if (!$entity->get('providerId')) {
- return;
- }
-
- $provider = $entity->getProvider();
-
- $scope = null;
+ $id = $request->getRouteParam('id') ?? throw new BadRequest();
- if ($provider->getScopes()) {
- $scope = implode($provider->getScopeSeparator() ?? ' ', $provider->getScopes());
- }
+ $account = $this->entityProvider->getByClass(OAuthAccount::class, $id);
- $data = [
- 'endpoint' => $provider->getAuthorizationEndpoint(),
- 'clientId' => $provider->getClientId(),
- 'redirectUri' => $this->configDataProvider->getRedirectUri(),
- 'scope' => $scope,
- 'prompt' => $provider->getAuthorizationPrompt(),
- 'params' => $provider->getAuthorizationParams(),
- ];
+ $data = $this->service->getAuthorizationData($account);
- $entity->set('data', $data);
+ return ResponseComposer::json($data);
}
}
diff --git a/application/Espo/Tools/OAuth/ConnectionService.php b/application/Espo/Tools/OAuth/ConnectionService.php
index dd6a8548d7..5a2d2bfe9b 100644
--- a/application/Espo/Tools/OAuth/ConnectionService.php
+++ b/application/Espo/Tools/OAuth/ConnectionService.php
@@ -29,19 +29,28 @@
namespace Espo\Tools\OAuth;
+use Espo\Core\Authentication\Oidc\PkceUtil;
use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\Forbidden;
+use Espo\Core\Session\Session;
use Espo\Entities\OAuthAccount;
+use Espo\Entities\OAuthProvider;
use Espo\ORM\EntityManager;
use GuzzleHttp\Exception\GuzzleException;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
+use League\OAuth2\Client\Provider\GenericProvider;
+use stdClass;
class ConnectionService
{
+ public const string SESSION_KEY_CODE_VERIFIER = 'oauthCodeVerifier';
+
public function __construct(
private EntityManager $entityManager,
private GenericProviderFactory $genericProviderFactory,
private TokenSetter $tokenSetter,
+ private Session $session,
+ private ConfigDataProvider $configDataProvider,
) {}
/**
@@ -56,7 +65,7 @@ class ConnectionService
throw new Forbidden("Provider is not active.");
}
- $genericProvider = $this->genericProviderFactory->create($provider);
+ $genericProvider = $this->prepareGenericProvider($provider);
try {
$tokens = $genericProvider->getAccessToken('authorization_code', ['code' => $code]);
@@ -79,4 +88,50 @@ class ConnectionService
$this->entityManager->saveEntity($account);
}
+
+ private function prepareGenericProvider(OAuthProvider $provider): GenericProvider
+ {
+ $genericProvider = $this->genericProviderFactory->create($provider);
+
+ if ($provider->useAuthorizationPkce()) {
+ $codeVerifier = $this->session->get(self::SESSION_KEY_CODE_VERIFIER);
+
+ $genericProvider->setPkceCode($codeVerifier);
+ }
+
+ return $genericProvider;
+ }
+
+ public function getAuthorizationData(OAuthAccount $account): stdClass
+ {
+ $provider = $account->getProvider();
+
+ $scope = null;
+
+ if ($provider->getScopes()) {
+ $scope = implode($provider->getScopeSeparator() ?? ' ', $provider->getScopes());
+ }
+
+ $codeChallenge = $provider->useAuthorizationPkce() ? $this->prepareCodeChallenge() : null;
+
+ return (object) [
+ 'endpoint' => $provider->getAuthorizationEndpoint(),
+ 'clientId' => $provider->getClientId(),
+ 'redirectUri' => $this->configDataProvider->getRedirectUri(),
+ 'scope' => $scope,
+ 'prompt' => $provider->getAuthorizationPrompt(),
+ 'params' => $provider->getAuthorizationParams(),
+ 'codeChallenge' => $codeChallenge,
+ 'codeChallengeMethod' => $codeChallenge ? 'S256' : null,
+ ];
+ }
+
+ private function prepareCodeChallenge(): string
+ {
+ $codeVerifier = PkceUtil::generateCodeVerifier();
+
+ $this->session->set(self::SESSION_KEY_CODE_VERIFIER, $codeVerifier);
+
+ return PkceUtil::hashAndEncodeCodeVerifier($codeVerifier);
+ }
}
diff --git a/client/src/views/o-auth-account/records/panels/connection.js b/client/src/views/o-auth-account/records/panels/connection.js
index f5fb074d9f..1abe2f768e 100644
--- a/client/src/views/o-auth-account/records/panels/connection.js
+++ b/client/src/views/o-auth-account/records/panels/connection.js
@@ -27,6 +27,8 @@
************************************************************************/
import SidePanelView from 'views/record/panels/side';
+import Ajax from 'ajax';
+import Ui from 'ui';
export default class OAuthAccountConnectionPanelView extends SidePanelView {
@@ -100,13 +102,13 @@ export default class OAuthAccountConnectionPanelView extends SidePanelView {
await this.reRender();
- Espo.Ui.notifyWait();
+ Ui.notifyWait();
- await Espo.Ajax.deleteRequest(`OAuth/${this.model.id}/connection`);
+ await Ajax.deleteRequest(`OAuth/${this.model.id}/connection`);
await this.model.fetch();
- Espo.Ui.notify();
+ Ui.notify();
this.inProcess = false;
@@ -117,37 +119,52 @@ export default class OAuthAccountConnectionPanelView extends SidePanelView {
* @private
*/
async actionConnect() {
- const data = this.model.attributes.data || {};
+ this.inProcess = true;
+ await this.reRender()
+
+ /**
+ * @type {{
+ * endpoint: string,
+ * clientId: string,
+ * redirectUri: string,
+ * scope: string|null,
+ * prompt: string,
+ * params: Record|null,
+ * codeChallenge: string|null,
+ * codeChallengeMethod: string|null,
+ * }}
+ */
+ let data;
+
+ try {
+ data = await Ajax.getRequest(`OAuth/${this.model.id}/authorizationData`);
+ } catch (e) {
+ this.inProcess = false;
+ await this.reRender();
- const endpoint = data.endpoint;
- const redirectUri = data.redirectUri;
- const clientId = data.clientId;
- const scope = data.scope;
- const prompt = data.prompt;
- const params = data.params;
+ return;
+ }
const proxy = window.open('about:blank', 'ConnectWithOAuth', 'location=0,status=0,width=800,height=800');
- const info = await this.processWithData({
- endpoint,
- redirectUri,
- clientId,
- scope,
- prompt,
- params,
- }, proxy);
+ let info
- this.inProcess = true;
+ try {
+ info = await this.processWithData(data, proxy);
+ } catch (e) {
+ this.inProcess = false;
+ await this.reRender();
- await this.reRender()
+ return;
+ }
- Espo.Ui.notifyWait();
+
+ Ui.notifyWait();
try {
- await Espo.Ajax.postRequest(`OAuth/${this.model.id}/connection`, {code: info.code});
+ await Ajax.postRequest(`OAuth/${this.model.id}/connection`, {code: info.code});
} catch (e) {
this.inProcess = false;
-
await this.reRender();
return;
@@ -155,10 +172,9 @@ export default class OAuthAccountConnectionPanelView extends SidePanelView {
await this.model.fetch();
- Espo.Ui.notify();
+ Ui.notify();
this.inProcess = false;
-
await this.reRender();
}
@@ -171,6 +187,8 @@ export default class OAuthAccountConnectionPanelView extends SidePanelView {
* scope: string|null,
* prompt: string,
* params: Record|null,
+ * codeChallenge: string|null,
+ * codeChallengeMethod: string|null,
* }} data
* @param {WindowProxy} proxy
* @return {Promise<{code: string}>}
@@ -189,6 +207,11 @@ export default class OAuthAccountConnectionPanelView extends SidePanelView {
params.scope = data.scope;
}
+ if (data.codeChallenge && data.codeChallengeMethod) {
+ params.code_challenge = data.codeChallenge;
+ params.code_challenge_method = data.codeChallengeMethod;
+ }
+
if (data.params) {
for (const name in data.params) {
params[name] = data.params[name];
@@ -249,21 +272,39 @@ export default class OAuthAccountConnectionPanelView extends SidePanelView {
if (!parsedData) {
fail();
- Espo.Ui.error('Could not parse URL', true);
+ Ui.error('Could not parse URL', true);
return;
}
if ((parsedData.error || parsedData.code) && state && parsedData.state !== state) {
fail();
- Espo.Ui.error('State mismatch', true);
+ Ui.error('State mismatch', true);
return;
}
if (parsedData.error) {
+ let message = parsedData.errorDescription ?? '';
+
+ if (message) {
+ message += '\n\n';
+ }
+
+ if (parsedData.error) {
+ message += '`' + parsedData.error + '`';
+ }
+
+ if (parsedData.code) {
+ if (parsedData.error) {
+ message += ' ';
+ }
+
+ message += parsedData.code;
+ }
+
fail();
- Espo.Ui.error(parsedData.errorDescription || this.translate('Error'), true);
+ Ui.error(message, true);
return;
}
@@ -298,7 +339,7 @@ export default class OAuthAccountConnectionPanelView extends SidePanelView {
code: params.get('code'),
state: params.get('state'),
error: params.get('error'),
- errorDescription: params.get('errorDescription'),
+ errorDescription: params.get('errorDescription') ?? params.get('error_description'),
};
} catch (e) {
return null;