I don't know if this is a bug in Magento 2 API or not, so I didn't post it on Magento 2 Github issues.
According to this link: http://devdocs.magento.com/guides/v2.0/get-started/authentication/gs-authentication-session.html:
Customers can access resources that are configured with anonymous or self permission in the webapi.xml configuration file.
I tried login Magento 2 storefront, then I went to magento_host/rest/V1/customers/me on the browser (which has "self" permission), I still got error
Consumer is not authorized to access %resources
I tried to create a custom API which also has "self" permission, I got the same error.
I'm using Magento 2.1.7.
Anyone know why? Thank you.
2 Answers 2
The session based authentication (with "self" permission) is only allowed to AJAX calls and not to browser requests due to security vulnerabilities.
-
1Thanks for the answer. Could you please share the example of it?Keyur Shah– Keyur Shah2017年12月04日 16:35:08 +00:00Commented Dec 4, 2017 at 16:35
Setting an additional header in your fetch does actually solve the issue, so
fetch('/rest/V1/customers/me', {headers: {"X-Requested-With": "XMLHttpRequest"}}).then(res => res.json()) //...
does actually succeed - like
jquery.ajax('/rest/V1/customers/me' // ...
would. To be sure about caches, my solution in the end was:
fetch('/rest/V1/customers/me?_='+(new Date().getTime()), {headers: {"X-Requested-With": "XMLHttpRequest"}}) // ...
The actual additional security is pretty much zero - but that's the way to go in M2
Explore related questions
See similar questions with these tags.