Please specify what version of the library you are using: [ ^2.0.6 ]
Please specify what version(s) of SharePoint you are targeting: [ Online ]
I am getting an unauthorized access error when trying to add users to the User Information List using sp.web.ensureUser on the site page, but not the work bench
On both my dev and production environments, I get the following error when I try to run my webpart on the sites home page:
{"error": {"code":"-2147024891, System.UnauthorizedAccessException","message":{"lang":"en-US","value":"Access denied. You do not have permission to perform this action or access this resource."}}}
I don't receive this error when I run the webpart in the workbench in either prod or dev environments.
I am trying to get the user id of the person filling out a form and the person in the people picker. All users have access to the form but not all in the User Information List
const spGetOriginator = await sp.web.ensureUser(this._webPartContext.pageContext.user.loginName);
const spGetRequestUser = await sp.web.ensureUser(requesterVals.RequestUser.Login);
Please let me know if there is anything you'd like me to try/test.
Thanks in advance for any help.
Just as an update, in the request headers the workbench is calling /_api/contextinfo for the current site. When is called in the site page, it tries to go up to the root site instead.
Webpart on site page:

webpart in workbench

Hi @jonesron, SPFx context should be established https://pnp.github.io/pnpjs/getting-started/#establish-context
Going to close this as answered. If you still have questions please open a new issue, ref this one and provide any additional details possible. Thanks!
Sorry for the delayed response since I was on PTO, but thank you @koltyakov. I originally had the context in the project for a different pnp call but removed it when I needed to change the code. When I established context again, ensureUser worked as it should.
This issue should still be considered closed, but why does it work in the workbench without establishing context?
thanks again for your help.
There is some logic involved to detect the site URL based on window location href. Which ends up with a correct value in case of the workbench. But that logic can't be extended to suit all the cases, so the context is the requirement for Modern UI.
Ok. that makes more sense. Again, thank you for your help.