Magento2: webapi admin authentication

Created on 5 Apr 2017  路  22Comments  路  Source: magento/magento2

Preconditions

magento 2.4-develop

The devdocs clearly state that authenticated admin users can access the rest api.

http://devdocs.magento.com/guides/v2.0/get-started/authentication/gs-authentication.html

Resources for which administrators or integrators are authorized. For example, if administrators are authorized for the Magento_Customer::group resource, they can make a GET /V1/customerGroups/:id call.

But this does not work.

Steps to reproduce

  1. Install magento 2.1.5 from composer archive
  2. Log into you new admin account
  3. Open domain.com/rest/V1/customers/1 in the same browser in a new tab.

Expected result

A response saying that this customer does not exist.

Actual result

A response saying me I have no acccess rights.

<response> <message>Consumer is not authorized to access %resources</message> <parameters> <resources>Magento_Customer::customer</resources> </parameters> </response>

Api Authorization Clear Description Confirmed Format is valid Ready for Work done Reproduced on 2.1.x Reproduced on 2.2.x Reproduced on 2.3.x Reproduced on 2.4.x

Most helpful comment

I debugged with xdebug, and found that the user context is null and chosen user context gets set to guest instead of admin. In AdminSessionUserContext $this->_adminSession->hasUser() returns null on a request although logged in.

.../module-authorization/Model/CompositeUserContext.php

    protected function getUserContext()
    {
        if ($this->chosenUserContext === null) {
            /** @var UserContextInterface $userContext */
            foreach ($this->userContexts as $userContext) {
                if ($userContext->getUserType() && $userContext->getUserId() !== null) {
                    $this->chosenUserContext = $userContext;
                    break;
                }
            }
            if ($this->chosenUserContext === null) {
                $this->chosenUserContext = false;
            }
        }
        return $this->chosenUserContext;
    }

.../module-user/Model/Authorization/AdminSessionUserContext.php

    public function getUserId()
    {
        return $this->_adminSession->hasUser() ? (int)$this->_adminSession->getUser()->getId() : null;
    }

All 22 comments

You need to provide header value to call rest API.
Try this on Postman or other tool with header value and it will work for you.

Header value in the form of an Integration (Bearer XXXX, which is what I already can do) or header value in the form of an admin user authentication?
I need information about the current logged in user in the api.

Ok, I see, It simply does not wotk like this. I need to use a token.

No, wait. It should be possible to just use the admin session. It is also clearly stated on the link I posted above

JavaScript widget on the Magento storefront or Magento Admin :
Registered users use session-based authentication to log in to the Magento storefront or Magento Admin.

Customers can access resources that are configured with anonymous or self permission in the webapi.xml configuration file.

Admins can access resources that are assigned to their Magento Admin profile.

Try {domain.com}/rest/V1/customers/me after login to your magento portal.

Admins can access resources that are assigned to their Magento Admin profile.

This is exactly what I say does not work. In the example above, in a freshly installed magento 2.1.5 the admin user created on install with role "Administrators" ist not allowed to access {domain.com}/rest/V1/customers/1.

Can you please verify in your installation that you can

  1. Log into magento as admin user with role "Administrators"
  2. Access rest api resources in another tab, session based

@skymeissner I guess that these samples will help you:
https://gist.github.com/rafaelstz/ecab668b80fece4d9acdb9c5358b3173

@skymeissner, were you ever able to figure this out?

I am having the same issues. I also see where the documentation clearly indicates that session-based authentication works to access admin resources.

Hi @DrewK289 ,

I did not get this to work, and I don't think it's possible at the moment. I switched to token based authentication, which works fine but I don't have info about logged-in admin user.

@skymeissner, thank you for your report.
This seems to be correct Magento behavior. Please refer to the Community Forums or the Magento Stack Exchange site for advice or general discussion about this.
Otherwise you may submit Pull Request with the suggested changes.

Please, look http://devdocs.magento.com/guides/v2.2/get-started/authentication/gs-authentication.html "Web API clients and authentication methods" - here you can see allowed authentication methods.

@magento-engcom-team
The behaviour is clearly stated otherwise in the documentation. In the link you posted above it reads "Each administrator or integration user can have a unique set of permissions which is configured in the Magento Admin." and "Administrator or Integration | Resources for which administrators or integrators are authorized."

adminorinteg

What refers "Administrator" to if not to a logged in admin user?

We've just hit this issue too.

I debugged with xdebug, and found that the user context is null and chosen user context gets set to guest instead of admin. In AdminSessionUserContext $this->_adminSession->hasUser() returns null on a request although logged in.

.../module-authorization/Model/CompositeUserContext.php

    protected function getUserContext()
    {
        if ($this->chosenUserContext === null) {
            /** @var UserContextInterface $userContext */
            foreach ($this->userContexts as $userContext) {
                if ($userContext->getUserType() && $userContext->getUserId() !== null) {
                    $this->chosenUserContext = $userContext;
                    break;
                }
            }
            if ($this->chosenUserContext === null) {
                $this->chosenUserContext = false;
            }
        }
        return $this->chosenUserContext;
    }

.../module-user/Model/Authorization/AdminSessionUserContext.php

    public function getUserId()
    {
        return $this->_adminSession->hasUser() ? (int)$this->_adminSession->getUser()->getId() : null;
    }

@skymeissner @davidwindell Did you find any solution/workaround?

Debugging further it seems like it has to do with duplicate cookies; the "PHPSESSID" cookie is used for the REST API but the "admin" cookie is used for admin. So authentication fails because the REST request reads from the wrong (PHPSESSID) session.

I have exact copy of magento 2 running on two different server.

Server 1:

Able to receive data correctly as I requested.
otherserver

Server 2:

I am getting error as:
"message": "Consumer is not authorized to access %resources","parameters": {"resources": "Magento_Customer::customer"}
simpleserver

@magento-engcom-team

Could someone from Magento let me know what their intentions with this issue are? I'm willing to take this one on as a community issue, however I am not 100% certain what a good fix would be.

Looking at the issue, the admin authorization is required in order to use any of the API's. Doing this from the /rest/* endpoint would, I think, never work, because the admin cookie is not available there.

My personal suggestion would be to create a new REST endpoint at /<admin-url>/rest/*which accepts the admin session as authorization, then forwards this to the default REST endpoint.

If someone from Magento could confirm to me that this would be a proper fix, I'll start on drafting a PR for this change.

@magento-engcom-team

Could someone from Magento let me know what their intentions with this issue are? I'm willing to take this one on as a community issue, however I am not 100% certain what a good fix would be.

Looking at the issue, the admin authorization is required in order to use any of the API's. Doing this from the /rest/* endpoint would, I think, never work, because the admin cookie is not available there.

My personal suggestion would be to create a new REST endpoint at /<admin-url>/rest/*which accepts the admin session as authorization, then forwards this to the default REST endpoint.

If someone from Magento could confirm to me that this would be a proper fix, I'll start on drafting a PR for this change.

I've been looking at Magento/Backend and Magento/Webapi and I'm not sure if the fix I've suggested here is possible at all, a few things I am not sure about on how to handle them are:

  • Magento/Webapi handles REST requests by adding an area and a controller for handling the API requests, which is not possible from inside the admin area
  • The admin features the secret key, which I do not think is compatible with making REST requests, due to this conflicting with the REST path

Will wait on @magento-engcom-team (or perhaps any other community member) to let me know what a possible vector to tackle this issue will be.

Hi @engcom-Alfa. Thank you for working on this issue.
Looks like this issue is already verified and confirmed. But if you want to validate it one more time, please, go though the following instruction:

  • [ ] 1. Add/Edit Component: XXXXX label(s) to the ticket, indicating the components it may be related to.
  • [ ] 2. 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_!

  • [ ] 3. If the issue is not relevant or is not reproducible any more, feel free to close it.


:white_check_mark: Confirmed by @engcom-Alfa
Thank you for verifying the issue. Based on the provided information internal tickets MC-30220 were created

Issue Available: @engcom-Alfa, _You will be automatically unassigned. Contributors/Maintainers can claim this issue to continue. To reclaim and continue work, reassign the ticket to yourself._

The documentation related to this issue has been updated in https://github.com/magento/devdocs/pull/7393
It seems we can close this old report.
But if a problem still exists, please create new report with an updated description and links related to 2.4

Was this page helpful?
0 / 5 - 0 ratings