2
votes

It's so simple:

  • OAuth protocol for authentication

  • list files from documentLibrary and checkout a file from the list

  • written in javascript

I've been struggling with this for few days with no such luck so far.

CHECKOUT OPTION 1 - Graph API:

https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_checkout

Even though it's OneDrive API, it's should be running with SharePoint doc.libraries as well - RESt APIs section: "The REST API is shared between OneDrive, OneDrive for Business, SharePoint document libraries, and Office Groups, to allow... "

The result? check it out here: Sharepoint `Unsupported segment type` when checkin/chekout file

Good news the OAuth works like a charm - I got the client ID from https://apps.dev.microsoft.com/, authentication endpoint:

https://login.microsoftonline.com/common/oauth2/v2.0/authorize https://login.microsoftonline.com/common/oauth2/v2.0/token

CHECKOUT OPTION 2 - Sharepoint Add-in

https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/working-with-folders-and-files-with-rest

url: http://site url/_api/web/GetFileByServerRelativeUrl('/Folder Name/file name')/CheckOut(),
method: POST
headers:
    Authorization: "Bearer " + accessToken
    X-RequestDigest: form digest value

This one works perfectly, but in this case, OAuth is the issue ...

this link is promising: https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/authorization-code-oauth-flow-for-sharepoint-add-ins

however, in the process, there is the Microsoft Azure Access Control Service (ACS) involved, which is (according to this link https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-acs-migration) about to switch off.

Solution seems to be is a switch to Azure application (https://portal.azure.com -> Azure Active Directory -> App registrations). Anyway, access token using these settings is not compatible with access token required for the Sharepoint API, e.g.:

https://mindjet2.sharepoint.com/_api/contextinfo throws exception 'Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException'

What I'm doing wrong with the graph api? What is the right way to authenticate the Sharepoint API using OAuth?

1

1 Answers

0
votes

In SharePoint add-in, we can use cross-domain library to achieve it.

Check the code below:

'use strict';  
var hostweburl;   
var appweburl;   

// This code runs when the DOM is ready and creates a context object which is   
// needed to use the SharePoint object model  
$(document).ready(function () {  

    //Get the URI decoded URLs.   
    hostweburl =   
    decodeURIComponent(   
    getQueryStringParameter("SPHostUrl"));   
    appweburl =   
    decodeURIComponent(   
    getQueryStringParameter("SPAppWebUrl"));   
    // Resources are in URLs in the form:  
    // web_url/_layouts/15/resource  
    var scriptbase = hostweburl + "/_layouts/15/";    

    // Load the js file and continue to load the page with information about the list top level folders.  
    // SP.RequestExecutor.js to make cross-domain requests  

    // Load the js files and continue to the successHandler  
    $.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);  
});  

// Function to prepare and issue the request to get  
//  SharePoint data  
function execCrossDomainRequest() {  
    // executor: The RequestExecutor object  
    // Initialize the RequestExecutor with the app web URL.  
    var executor = new SP.RequestExecutor(appweburl);             

    var metatdata = "{ '__metadata': { 'type': 'SP.Data.TestListListItem' }, 'Title': 'changelistitemtitle'}";  

    // Issue the call against the app web.  
    // To get the title using REST we can hit the endpoint:  
    //      appweburl/_api/web/lists/getbytitle('listname')/items  
    // The response formats the data in the JSON format.  
    // The functions successHandler and errorHandler attend the  
    //      sucess and error events respectively.  
    executor.executeAsync({            
        url:appweburl + "/_api/SP.AppContextSite(@target)/web/GetFileByServerRelativeUrl('/Shared Documents/a.txt')/CheckOut()?@target='" +    
        hostweburl + "'",    
        method: "POST",    
        body: metatdata ,    
        headers: { "Accept": "application/json; odata=verbose", "content-type": "application/json; odata=verbose", "content-length": metatdata.length, "X-HTTP-Method": "MERGE", "IF-MATCH": "*" },            
        success: function (data) {  
            alert("success: " + JSON.stringify(data));  
        },  
        error: function (err) {  
            alert("error: " + JSON.stringify(err));  
        }    
    });
}                    
// This function prepares, loads, and then executes a SharePoint query to get   
// the current users information        
//Utilities   

// Retrieve a query string value.   
// For production purposes you may want to use   
// a library to handle the query string.   
function getQueryStringParameter(paramToRetrieve) {   
    var params =document.URL.split("?")[1].split("&");     
    for (var i = 0; i < params.length; i = i + 1) {   
        var singleParam = params[i].split("=");   
        if (singleParam[0] == paramToRetrieve)   
        return singleParam[1];   
    }   
} 

Reference:https://www.c-sharpcorner.com/UploadFile/472cc1/check-out-files-in-sharepoint-library-2013-using-rest-api/