Skip to content

The consumer isn't authorized to access %resources. Magento 2.4.5-p1 on staging environment #38426

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
5 tasks
nilaykumardeveloper opened this issue Feb 6, 2024 · 20 comments
Labels
Area: APIs Component: order status Issue: Confirmed Gate 3 Passed. Manual verification of the issue completed. Issue is confirmed Priority: P2 A defect with this priority could have functionality issues which are not to expectations. Progress: ready for dev Reported on 2.4.x Indicates original Magento version for the Issue report. Reproduced on 2.4.x The issue has been reproduced on latest 2.4-develop branch

Comments

@nilaykumardeveloper
Copy link

Summary

In the testing environment, it gives below errors,

{
"message": "The consumer isn't authorized to access %resources.",
"parameters": {
    "resources": "Magento_Sales::actions_view"
},
"trace": "#0 /var/www/html/vendor/magento/module-webapi/Controller/Rest/RequestValidator.php(68): Magento\\Webapi\\Controller\\Rest\\RequestValidator->checkPermissions()\n#1 /var/www/html/vendor/magento/framework/Interception/Interceptor.php(58): Magento\\Webapi\\Controller\\Rest\\RequestValidator->validate()\n#2 /var/www/html/vendor/magento/framework/Interception/Interceptor.php(138): Magento\\Webapi\\Controller\\Rest\\RequestValidator\\Interceptor->___callParent('validate', Array)\n#3 /var/www/html/vendor/paypal/module-braintree-core/Plugin/RestValidationPlugin.php(86): Magento\\Webapi\\Controller\\Rest\\RequestValidator\\Interceptor->Magento\\Framework\\Interception\\{closure}()\n#4 /var/www/html/vendor/magento/framework/Interception/Interceptor.php(135): PayPal\\Braintree\\Plugin\\RestValidationPlugin->aroundValidate(Object(Magento\\Webapi\\Controller\\Rest\\RequestValidator\\Interceptor), Object(Closure))\n#5 /var/www/html/vendor/magento/framework/Interception/Interceptor.php(153): Magento\\Webapi\\Controller\\Rest\\RequestValidator\\Interceptor->Magento\\Framework\\Interception\\{closure}()\n#6 /var/www/html/generated/code/Magento/Webapi/Controller/Rest/RequestValidator/Interceptor.php(23): Magento\\Webapi\\Controller\\Rest\\RequestValidator\\Interceptor->___callPlugins('validate', Array, NULL)\n#7 /var/www/html/vendor/magento/module-webapi/Controller/Rest/InputParamsResolver.php(108): Magento\\Webapi\\Controller\\Rest\\RequestValidator\\Interceptor->validate()\n#8 /var/www/html/vendor/magento/framework/Interception/Interceptor.php(58): Magento\\Webapi\\Controller\\Rest\\InputParamsResolver->resolve()\n#9 /var/www/html/vendor/magento/framework/Interception/Interceptor.php(138): Magento\\Webapi\\Controller\\Rest\\InputParamsResolver\\Interceptor->___callParent('resolve', Array)\n#10 /var/www/html/vendor/magento/framework/Interception/Interceptor.php(153): Magento\\Webapi\\Controller\\Rest\\InputParamsResolver\\Interceptor->Magento\\Framework\\Interception\\{closure}()\n#11 /var/www/html/generated/code/Magento/Webapi/Controller/Rest/InputParamsResolver/Interceptor.php(23): Magento\\Webapi\\Controller\\Rest\\InputParamsResolver\\Interceptor->___callPlugins('resolve', Array, Array)\n#12 /var/www/html/vendor/magento/module-webapi/Controller/Rest/SynchronousRequestProcessor.php(85): Magento\\Webapi\\Controller\\Rest\\InputParamsResolver\\Interceptor->resolve()\n#13 /var/www/html/vendor/magento/module-webapi/Controller/Rest.php(195): Magento\\Webapi\\Controller\\Rest\\SynchronousRequestProcessor->process(Object(Magento\\Framework\\Webapi\\Rest\\Request\\Proxy))\n#14 /var/www/html/vendor/magento/framework/Interception/Interceptor.php(58): Magento\\Webapi\\Controller\\Rest->dispatch(Object(Magento\\Framework\\App\\Request\\Http))\n#15 /var/www/html/vendor/magento/framework/Interception/Interceptor.php(138): Magento\\Webapi\\Controller\\Rest\\Interceptor->___callParent('dispatch', Array)\n#16 /var/www/html/vendor/magento/framework/Interception/Interceptor.php(153): Magento\\Webapi\\Controller\\Rest\\Interceptor->Magento\\Framework\\Interception\\{closure}(Object(Magento\\Framework\\App\\Request\\Http))\n#17 /var/www/html/generated/code/Magento/Webapi/Controller/Rest/Interceptor.php(23): Magento\\Webapi\\Controller\\Rest\\Interceptor->___callPlugins('dispatch', Array, Array)\n#18 /var/www/html/vendor/magento/framework/App/Http.php(116): Magento\\Webapi\\Controller\\Rest\\Interceptor->dispatch(Object(Magento\\Framework\\App\\Request\\Http))\n#19 /var/www/html/vendor/magento/framework/App/Bootstrap.php(264): Magento\\Framework\\App\\Http->launch()\n#20 /var/www/html/pub/index.php(30): Magento\\Framework\\App\\Bootstrap->run(Object(Magento\\Framework\\App\\Http\\Interceptor))\n#21 {main}"

}

Its already Yes in: Allow OAuth Access Tokens.

I tried it in PHP script with Integration user as well as bearer token and not working in both scenario. The main thing is that live and local environment looks fine with same code file and DB setup.

So my concern is that, Is any configuration on server can impact on this?

PHP script:

<?php  

function sign($method, $url, $data, $consumerSecret, $tokenSecret)
{
$url = urlEncodeAsZend($url);
$data = urlEncodeAsZend(http_build_query($data, '', '&'));
$data = implode('&', [$method, $url, $data]);
$secret = implode('&', [$consumerSecret, $tokenSecret]);
return base64_encode(hash_hmac('sha256', $data, $secret, true));
}
function urlEncodeAsZend($value)
{
$encoded = rawurlencode($value);
$encoded = str_replace('%7E', '~', $encoded);
return $encoded;
}
// REPLACE WITH YOUR ACTUAL DATA OBTAINED WHILE CREATING NEW INTEGRATION

$consumerKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
$consumerSecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
$accessToken = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
$accessTokenSecret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX';
$method = 'GET';
$url = 'http://xxxx.staging.com/rest/V1/orders/38024';

$data = [
'oauth_consumer_key' => $consumerKey,
'oauth_nonce' => md5(uniqid(rand(), true)),
'oauth_signature_method' => 'HMAC-SHA256',
'oauth_timestamp' => time(),
'oauth_token' => $accessToken,
'oauth_version' => '1.0',
];
$data['oauth_signature'] = sign($method, $url, $data, $consumerSecret, $accessTokenSecret);
//print_r($data);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => [
'Authorization: OAuth ' . http_build_query($data, '', ',')
]
]);
$result = curl_exec($curl);
$orderData = json_decode($result,true);
curl_close($curl);
echo '

';
print_r($result);
echo '
';

?>
POSTMAN:
enter image description here

Examples

`

$consumerKey, 'oauth_nonce' => md5(uniqid(rand(), true)), 'oauth_signature_method' => 'HMAC-SHA256', 'oauth_timestamp' => time(), 'oauth_token' => $accessToken, 'oauth_version' => '1.0', ]; $data['oauth_signature'] = sign($method, $url, $data, $consumerSecret, $accessTokenSecret); //print_r($data); $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => $url, CURLOPT_HTTPHEADER => [ 'Authorization: OAuth ' . http_build_query($data, '', ',') ] ]); $result = curl_exec($curl); $orderData = json_decode($result,true); curl_close($curl); echo '
';
 print_r($result);
 echo '
'; ?>`

I tried it in the PHP script with the Integration user as well as the bearer token and it did not work in both scenarios. The main thing is that the live and local environment looks fine with the same code file and DB setup.

So my concern is that, Is any configuration on server can impact on this?

Proposed solution

No response

Release note

No response

Triage and priority

  • Severity: S0 - Affects critical data or functionality and leaves users without workaround.
  • Severity: S1 - Affects critical data or functionality and forces users to employ a workaround.
  • Severity: S2 - Affects non-critical data or functionality and forces users to employ a workaround.
  • Severity: S3 - Affects non-critical data or functionality and does not force users to employ a workaround.
  • Severity: S4 - Affects aesthetics, professional look and feel, “quality” or “usability”.
@nilaykumardeveloper nilaykumardeveloper added the Triage: Dev.Experience Issue related to Developer Experience and needs help with Triage to Confirm or Reject it label Feb 6, 2024
Copy link

m2-assistant bot commented Feb 6, 2024

Hi @nilaykumardeveloper. Thank you for your report.
To speed up processing of this issue, make sure that the issue is reproducible on the vanilla Magento instance following Steps to reproduce. To deploy vanilla Magento instance on our environment, Add a comment to the issue:


Join Magento Community Engineering Slack and ask your questions in #github channel.
⚠️ According to the Magento Contribution requirements, all issues must go through the Community Contributions Triage process. Community Contributions Triage is a public meeting.
🕙 You can find the schedule on the Magento Community Calendar page.
📞 The triage of issues happens in the queue order. If you want to speed up the delivery of your contribution, join the Community Contributions Triage session to discuss the appropriate ticket.

@engcom-Bravo engcom-Bravo added the Reported on 2.4.x Indicates original Magento version for the Issue report. label Feb 7, 2024
@engcom-Bravo engcom-Bravo self-assigned this Feb 7, 2024
Copy link

m2-assistant bot commented Feb 7, 2024

Hi @engcom-Bravo. Thank you for working on this issue.
In order to make sure that issue has enough information and ready for development, please read and check the following instruction: 👇

  • 1. Verify that issue has all the required information. (Preconditions, Steps to reproduce, Expected result, Actual result).
  • 2. Verify that issue has a meaningful description and provides enough information to reproduce the issue.
  • 3. Add Area: XXXXX label to the ticket, indicating the functional areas it may be related to.
  • 4. Verify that the issue is reproducible on 2.4-develop branch
    Details- Add the comment @magento give me 2.4-develop instance to deploy test instance on Magento infrastructure.
    - If the issue is reproducible on 2.4-develop branch, please, add the label Reproduced on 2.4.x.
    - If the issue is not reproducible, add your comment that issue is not reproducible and close the issue and stop verification process here!
  • 5. Add label Issue: Confirmed once verification is complete.
  • 6. Make sure that automatic system confirms that report has been added to the backlog.

@engcom-Bravo engcom-Bravo removed the Triage: Dev.Experience Issue related to Developer Experience and needs help with Triage to Confirm or Reject it label Feb 7, 2024
@engcom-Bravo
Copy link
Contributor

@magento give me 2.4-develop instance

Copy link

Hi @engcom-Bravo. Thank you for your request. I'm working on Magento instance for you.

Copy link

@engcom-Bravo
Copy link
Contributor

Hi @nilaykumardeveloper,

Thank you for reporting and collaboration.

Verified the issue on Magento 2.4-develop instance and the issue is reproducible.Kindly refer the attached screenshots.

Screenshot from 2024-02-07 14-20-35

We have given access for all the resources still we are getting the error.

Hence Confirming the issue.

Thanks.

@engcom-Bravo engcom-Bravo added Area: APIs Component: order status Reproduced on 2.4.x The issue has been reproduced on latest 2.4-develop branch Issue: Confirmed Gate 3 Passed. Manual verification of the issue completed. Issue is confirmed Priority: P2 A defect with this priority could have functionality issues which are not to expectations. labels Feb 7, 2024
@github-jira-sync-bot
Copy link

✅ Jira issue https://jira.corp.adobe.com/browse/AC-10997 is successfully created for this GitHub issue.

Copy link

m2-assistant bot commented Feb 7, 2024

✅ Confirmed by @engcom-Bravo. Thank you for verifying the issue.
Issue Available: @engcom-Bravo, You will be automatically unassigned. Contributors/Maintainers can claim this issue to continue. To reclaim and continue work, reassign the ticket to yourself.

@nilaykumardeveloper
Copy link
Author

Sure! If anyone has any suggestions, please let me know. Your input would be greatly appreciated.

@thomas-kl1
Copy link
Member

Related issue: #36811

@WCL-joejones
Copy link

HI Guys

just wondering if theres any time estimation on this?

Kind Regards,
Joe

@bkuermayr
Copy link

need a fix on this too

@siliconalchemy
Copy link

@engcom-Bravo - has there been any internal development on this issue, is there a workaround? It has completely broken integration with Magento for me, it's a really major bug.

@luka4
Copy link

luka4 commented May 2, 2024

Looks like issue is related to when your storefront URL is not same as your base url at "All Stores View".
For me it is still actual for 2.4.6-p4 EE

@craig-bartlett
Copy link
Contributor

Looks like issue is related to when your storefront URL is not same as your base url at "All Stores View". For me it is still actual for 2.4.6-p4 EE

Same for me on 2.4.5-p8 CE. Base URL is fine but storefront URL throws the error.

@lionalex
Copy link

There is not a solution? WIth magento 2.4.7 and 2.4.6 same error. Is really important bug.

@siliconalchemy
Copy link

Looks like issue is related to when your storefront URL is not same as your base url at "All Stores View". For me it is still actual for 2.4.6-p4 EE

This occurs for all store URLs for me.

There is not a solution? WIth magento 2.4.7 and 2.4.6 same error. Is really important bug.

Seems insane that this major bug isn't being addressed. This is an open issue, P2 priority, confirmed, reproduced and sitting in high priority backlog for nearly half a year.

As a workaround, I hack vendor/magento/module-webapi/Controller/Rest/RequestValidator.php, and add an extra validator:

        $headers = $this->request->getHeaders()->toString();
        if (str_contains($headers, 'changethispasswordtoarandomsetofsquiggles')) {
            return;
        }

And then when I make a REST call, I add an extra header in the call:

            res = requests.get(
                url+"?"+urlparam, verify=self._verify_ssl,
                headers={
                    'Authorization': 'Bearer %s' % self._token,
                    'TempAuth': 'changethispasswordtoarandomsetofsquiggles',
                })

Obviously this isn't ideal as it's a reusable symmetric cleartext password and bypasses finegrained ACL, but at least it works for now..

@engcom-Hotel engcom-Hotel moved this to Ready for Development in High Priority Backlog Aug 19, 2024
@Paulsky
Copy link

Paulsky commented Oct 22, 2024

Any update on this?

@Paulsky
Copy link

Paulsky commented Oct 23, 2024

The only workaround I now see is the following. If you use the option 'Allow OAuth Access Tokens to be used as standalone Bearer tokens'. And you trust the integration party. You can bypass the (false negative) exception. I would ask the third party for their IP's and do the following:

Inside module-webapi/Controller/Rest/RequestValidator.php change 'checkPermissions()' and add a custom function:

/**
     * Perform authentication and authorization.
     *
     * @return void
     * @throws \Magento\Framework\Exception\AuthorizationException
     */
    private function checkPermissions()
    {
        $route = $this->router->match($this->request);
        if (!$this->authorization->isAllowed($route->getAclResources())) {

            //CUSTOM
            if ($this->isFullyTrustedToken()) {
                return;
            }

            $params = ['resources' => implode(', ', $route->getAclResources())];
            throw new AuthorizationException(
                __("The consumer isn't authorized to access %resources.", $params)
            );
        }
    }

    /**
     * CUSTOM
     * 
     * @return bool
     */
    private function isFullyTrustedToken()
    {
        $trustedTokens = [
            'token1' => ['ip1', 'ip2'], //integration 1
            'token2' => ['ip1', 'ip3']  //integration 2
        ];

        //See module-webapi/Model/Authorization/TokenUserContext processRequest()
        $authorizationHeaderValue = $this->request->getHeader('Authorization');
        if (!$authorizationHeaderValue) {
            return false;
        }

        $headerPieces = explode(" ", $authorizationHeaderValue);
        if (count($headerPieces) !== 2) {
            return false;
        }

        $tokenType = strtolower($headerPieces[0]);
        if ($tokenType !== 'bearer') {
            return false;
        }

        $bearerToken = $headerPieces[1];

        //See framework/HTTP/PhpEnvironment/Request.php getClientIp()
        $clientIp = $this->request->getClientIp();

        // Check if token exists and IP is allowed for that token
        if (isset($trustedTokens[$bearerToken]) && in_array($clientIp, $trustedTokens[$bearerToken])) {
            return true;
        }

        return false;
    }

Needless to say; be careful. I do not have tested this a lot. Use at your own risk.

@fabianaromagnoli
Copy link

I had the same issue when upgrading from Magento 2.4.2 to 2.4.7. From what I understand, security has been reinforced in the latest versions, and OAuth tokens can no longer be used as Bearer tokens by default. You need to explicitly change the settings to allow this behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Area: APIs Component: order status Issue: Confirmed Gate 3 Passed. Manual verification of the issue completed. Issue is confirmed Priority: P2 A defect with this priority could have functionality issues which are not to expectations. Progress: ready for dev Reported on 2.4.x Indicates original Magento version for the Issue report. Reproduced on 2.4.x The issue has been reproduced on latest 2.4-develop branch
Projects
None yet
Development

No branches or pull requests