sharepointunauthorizedaccessexcepti

UnauthorizedAccessException when asking sharepoint for items in a list


I am trying to access list's items in my sharepoint site. I have created a clientId and a secretId on the page "https://XXXXXX.sharepoint.com/sites/XXXXX/_layouts/15/appregnew.aspx". Then I create the access rule on the page "https://XXXXX.sharepoint.com/sites/XXXXX/_layouts/15/appinv.aspx". On this page, I set the XML code for the access rule like is :

<AppPermissionRequests><AppPermissionRequest 
   Scope="http://sharepoint/content/sitecollection" 
   Right="FullControl"/></AppPermissionRequests>

I create the rule and confirm it on the next page.

In my app, I get the token with this code

let payload = `grant_type=client_credentials
            &client_id=${clientId}@${tenantId}
            &client_secret=${clientSecret}
&resource=${resource}/${domain}@${tenantId}`;
        let authOptions = {
            hostname: 'accounts.accesscontrol.windows.net',
            path: `/${tenantId}/tokens/OAuth/2`,
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(payload)
            }
        };
        let req = https.request(authOptions, res => {...})

then I do this to get the items in my list :

let listOptions = {
        hostname: 'XXXXX.sharepoint.com',
        path: '/sites/XXX/_api/lists/getbytitle('MyList')/items',
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `bearer ${accessToken}`,
            'Accept': 'application/json'
        }
    };
    let req = https.request(listOptions, res => {
        res.setEncoding('utf8');
        let stringResult = '';
        res.on('data', chunk => {
            stringResult += chunk.toString();
        });

Sharepoint always return this error

"{"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."}}}"

Solution

  • I finally found why it doesn't work. I needed to add AllowAppOnlyPolicy :

    <AppPermissionRequests AllowAppOnlyPolicy="true">
    <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl" />