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://learn.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://learn.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://learn.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://learn.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?
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/
Related
I want get authentication token using REST API or session based authentication for an app or organization of Azure DevOps on SharePoint webpart page. I want some other ways to authenticate REST API of an organization except Personal Access Token (PAT) method. Can you please help me to give a solution of it? If possible please provide an example/demo of it in JavaScript/JQuery.
I had added an example in which I am using personal Access Token (PAT) to get Projects of an organization
on a SharePoint page
var PATToken = 'xxxx7xxxx6xxxxx7xxxxxxx2xxx';//user need to replace his Personal Access Token here and run this snippent on SharePoint Page.
var orgName = 'TestRaju';
getOrgProjects(orgName);
function getOrgProjects(orgName) {
$.ajax({
url: 'https://dev.azure.com/' + orgName + '/_apis/projects?api-version=5.1',
dataType: 'json',
headers: {
'Authorization': 'Basic ' + btoa("" + ":" + PATToken)
}
}).success(function (results) {
console.log(results);
}).error(function (error) {
console.log(error);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You may try OAuth token:
https://learn.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/oauth?view=azure-devops
User Authorizes your Application
At a high-level, you call the "authorize" endpoint and provide a callback. The callback must be a secure url (https) in your application:
https://app.vssps.visualstudio.com/oauth2/authorize
?client_id={app ID}
&response_type=Assertion
&state={state}
&scope={scope}
&redirect_uri={callback URL}
Assuming the user accepts the authorization, Azure DevOps redirects to your callback location with the authorization code in the URL.
https://fabrikam.azurewebsites.net/myapp/oauth-callback
?code={authorization code}
&state={state}
You may refer to the following case:
Access Azure DevOps REST API with oAuth
I am creating a simple web page, that make use of the Google Translation Service.
The page has a field, to receive the input from the user and a button to trigger the call to the Translation API. It returns the result translation to the user.
I've successfully done the flow above using Ajax requests, but the access token
is hard-coded into my method and I want to change that to a call that gets sent whenever the token expires (currently I have to request a new token using the Google CLI and replace it in my code).
I have a very basic knowledge of Oauth2.0 and I've read the Google Documentation but couldn't find a part of it that would tell me the endpoint to call to get an access token from the client-side.
Could someone point me in the right direction, please?
Here is my code:
HTML:
<form id="translate_form">
<input id="input" />
<button id="translate_button">Translate</button>
</form>
Javascript
$("#translate_form").submit(function () {
var text = $("#input").val()
sendTranslationRequest(text);
return false;
})
function sendTranslationRequest(inputText) {
var requestBody = {
q: inputText,
source: "en",
target: "fr",
format: 'text'
}
translationAjaxRequest(requestBody);
}
function translationAjaxRequest(requestBody) {
var access_token = [access_token]
$.ajax({
url: "https://translation.googleapis.com/language/translate/v2",
method: "POST",
contentType: "application/json",
beforeSend: function (request) {
request.setRequestHeader("Authorization", "Bearer " + access_token)
},
data: JSON.stringify(requestBody),
success: function (response) {
var translatedText = response.data.translations[0].translatedText
alert(translatedText)
},
error: function () {
console.log("An error occurred on the request:", response)
}
});
}
The relevant endpoints to get an access token and refresh it are:
https://accounts.google.com/o/oauth2/v2/auth
https://www.googleapis.com/oauth2/v4/token
However, you’ll need to perform several steps in order to get an access token and a refresh token. You may want to review this guide on Using OAuth2.0 for Web Server Applications. It will walk you through the prerequisites, obtaining an access token and refreshing your token.
Alternatively, you may use an API Key. Just be mindful of the recommendations on how to secure it, since a stolen API Key may be used to generate calls that would be charged directly to your billing account.
I am trying to access the Submit API that is apart of the Google Cloud Print however I am running into the error "User credentials required".
I am able to get all the way through authentication and am able to retrieve my access token. I was following this guide https://developers.google.com/cloud-print/docs/appDevGuide
I do not know where it is going wrong. Does anyone know where the credentials are supposed to be inputted?
Here is my code for this portion:
function submitPrintJob(token){
try{
var params = {'printerid':'PRINTER_ID','title':'Test Print Job','ticket':{"version": "1.0", "print": {}},'contentType':'application/pdf'};
var response = https.post({
url: 'https://www.google.com/cloudprint/submit',
body: params,
headers: {'Authorization':'Bearer ' + token}
});
log.debug('submitPrintJob','Response - ' + response.body);
}catch(e){
log.error('submitPrintJob','Error - ' + e.message);
}
}
This code is being in done in Netsuite which is where the https.post API is coming in. I also am aware that I am not sending a document through but I at least need to get past this step. I am getting this error using Postman as well.
Editing to add the portion where I get the token:
I send a request to: https://accounts.google.com/o/oauth2/v2/auth
Parameters:
response_type: code,
scope: https://www.googleapis.com/auth/cloud-platform.read-only,
state: state_parameter_passthrough_value,
redirect_uri: scriplet url
client_id: client id
Google oauth returns a authorization code. I exchange the code for a token this way:
function getToken(code){
try{
var params = {'code':code,'client_id':CLIENT_ID,'client_secret':CLIENT_SECRET,'redirect_uri':REDIRECT_URI,'grant_type':'authorization_code'}
var response = https.post({
url: 'https://www.googleapis.com/oauth2/v4/token',
body: params,
headers: {'Content-Type':'application/x-www-form-urlencoded'}
});
var token = response.body.access_token;
submitPrintJob(token);
}catch(e){
log.error('getAuthCode','Error - ' + e.message);
}
}
As I thought, the problem is how you are getting the access token. In order to get a valid access token to do your cloud print business, you need to include the proper scope. That means that your params object should like like this:
var params = {'code':code,'client_id':CLIENT_ID,'client_secret':CLIENT_SECRET,'redirect_uri':REDIRECT_URI, 'scope': 'https://www.googleapis.com/auth/cloudprint', 'grant_type':'authorization_code'}
This should give you a valid access token to interact with Google Cloud Print. I hope it helps!
I'm building a content panel app for Office.
Part of that requires authenticating an account against a server. I've implemented my own AuthorizationFilterAttribute on my web api 2 controllers, and called config.EnableCors(new EnableCorsAttribute("*", "*", "*")); on my web api registration.
I built a test script that fires a simple get at an endpoint and I can get it to work in chrome and ie.
var token = btoa(username + ':' + password);
$.ajax({
url: 'http://www.someendpoint/',
type: 'GET',
beforeSend: function (request) {
request.setRequestHeader("Authorization", "Basic " + token);
},
success: function (data) {
return true;
},
error: function (data) {
return false;
}
});
Problem is that it doesn't work in the app.
The error: function is being hit and the data contains "Error: Access is denied.\r\n"
I've attempted to use $.support.cors = true; in addition to ensuring the domain name is given permission in the App Manifest.
Anyone have any ideas on what else to try?
So it turns out that in the project properties, office apps enforce SSL by default, which is great to be honest, but not ideal when testing against a non SSL domain.
The answer to this is to adjust the project settings as shown below.
I have a tiny project on school that has only two "kinds" to store :Site - Position. Each of them has only a string content.
My problem that I want to get ALL the stored data from datastore of these two kinds from javascript file.
I tried the following:
function getData(syncedData) {
// reset the observable
syncedData();
// set the ajax
var options = {
url: 'https://www.googleapis.com/datastore/v1beta2/datasets/{my-project-id}/runQuery?key=AIzaSyCHeg3tkyEENxAXKsl1xilX19BreDxWFzg',
type: 'POST',
dataType: 'application/json',
data:'{ "query": { }}'
};
// call the ajax
return $.ajax(options)
.then(querySucceeded)
.fail(queryFailed);
// handle the ajax callback
function querySucceeded(data) {
syncedData(data);
log('Sync data succeeded', sites, true);
}
function queryFailed(jqXHR, textStatus) {
log('Sync data Error. ' + textStatus, jqXHR, true);
}
}
where the "key=AIzaSyCHeg3tkyEENxAXKsl1xilX19BreDxWFzg" is API Key I created as Public API access from Cloud Console; I really need any one can query this results.
But using the above gives me 401 (Unauthorized) at Chrome Console.
How can I query these results and make it PUBLIC;
Must I use OAuth API? any clear steps of using 'not the google-docs'?! and how to make it PUBLIC ACCESSED?!