How to use access token during making GET Request to Sharepoint file? - javascript

i use sharepoint as cloud storage. I have a few .pdf files there now, and gave them public accessibility. So i'm available to open file by this url in anonymous window.
I need to use current files in another system (Salesforce), and i need to make api callouts to GET those files(base64).
I got access_token by this endpoint: https://accounts.accesscontrol.windows.net
Postman Request Image
This is file public url: https://lpnu-my.sharepoint.com/personal/marian_lyzhychka_mtrte_2021_edu_lpnu_ua/_layouts/15/onedrive.aspx?id=%2Fpersonal%2Fmarian%5Flyzhychka%5Fmtrte%5F2021%5Fedu%5Flpnu%5Fua%2FDocuments%2FWhoMovedMyCheese%281%29%2Epdf&parent=%2Fpersonal%2Fmarian%5Flyzhychka%5Fmtrte%5F2021%5Fedu%5Flpnu%5Fua%2FDocuments&ga=1
When i tried to send GET request to this endpoint and set received Access_token as bearer token, i received 401 (Unauthorized).
I am available to get file if i get cookie from developer tools, and set as header. But for every file cookies are different and it work's for me only for testing.
Could you please explain me what i do wrong? And how to access public files via request (JavaScript). Thank you!

According to my research and testing, when you generate the access_token, are permissions granted to the add-in, and what permissions are granted?
Please try granting Full Control permission, for example: enter the below XML in the “Permission Request XML” box:
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" />
</AppPermissionRequests>
If you want to get files in SharePoint, you can use the following Rest API:
GET https://{site_url}/_api/web/lists/GetByTitle('Test')/items
Authorization: "Bearer " + accessToken
Accept: "application/json;odata=verbose"
If you want to get a specific file, you can use the following REST API:
GET https://{site_url}/_api/web/lists/GetByTitle('Test')/items({item_id})
Authorization: "Bearer " + accessToken
Accept: "application/json;odata=verbose"
More information for reference:
Rest API: Working with lists and list items with REST
Generate access-token and access SharePoint: In 4 steps access SharePoint online data using postman tool
Similar issue for reference: How to use access token during making GET Request to Sharepoint file?
Note: Microsoft is providing this information as a convenience to you. The sites are not controlled by Microsoft. Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. Please make sure that you completely understand the risk before retrieving any suggestions from the above link.

Related

How to authorize amazon pay request to "get checkout session"?

I've been trying to integrate Amazon pay as a payment method for customers on my website but am running into issues with some of what's detailed in the documentation. I'm hoping to better understand the request headers that are to be associated with a call to the amazon pay api.
I'm making a request to 'https://pay-api.amazon.com/v2/checkoutSessions/checkoutSessionId' and receiving a CORS policy error.
Access to fetch at 'https://pay-api.amazon.com/v2/checkoutSessions/d9b4418d-0c6f-4085-8c37-08bef6da6807' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Here is the fetch request where I am trying to make the request
fetch(`https://pay-api.amazon.com/v2/checkoutSessions/${this.$route.query.amazonCheckoutSessionId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'authorization': 'Px2e5oHhQZ88vVhc0DO%2FsShHj8MDDg%3DEXAMPLESIGNATURE',
'x-amz-pay-date': `${new Date()}`
}
})
this.$route.query.amazonCheckoutSessionId references the returned url extension after the user creates a checkout session using the amazon pay button.
The documentation outlines a request should be made as follows
curl "https://pay-api.amazon.com/:version/checkoutSessions/:checkoutSessionId"
-X GET
-H "authorization:Px2e5oHhQZ88vVhc0DO%2FsShHj8MDDg%3DEXAMPLESIGNATURE"
-H "x-amz-pay-date:20201012T235046Z"
Can someone please explain where I'm supposed to get the authorization string and its format? Also, is there a way to easily format a date string into the format displayed in the documentation? Or does the date string format not matter?
I have searched quite extensively through the stack overflow posts associated with Amazon pay (of which there are few) as well as searching other Amazon and AWS documentation for elaboration on how to format the auth string. Unfortunately, I can't seem to find an answer. I have also tried passing my button signature as my authorization string, but that didn't seem to help.
Thank you for any help you can give.
There are two parts to your problem:
The API is not designed to listen to Browser JS (AJAX) requests as in your sample. The CORS restriction is in place to prevent this. Rather this part of the process is to be done on the server side
To use the API, I would strongly recommend using one of the SDKs (https://pay.amazon.co.uk/help/201212390?ld=APUKLPADirect). You will notice in the docs (https://developer.amazon.com/docs/amazon-pay-checkout/add-the-amazon-pay-button.html), that they always have the code samples for all four offered SDKs. So it is much easier to follow those instructions.
The Amazon Pay API's do not support direct client side requests, so you'll need to make those requests server side. That's why you're seeing a CORS error.
You can find a detailed walk through on the signature generation required to sign each of the API requests here: https://developer.amazon.com/docs/amazon-pay-api-v2/signing-requests.html
You should be able to leverage the Amazon Pay Node.js SDK, which will save quite a bit of coding - https://developer.amazon.com/docs/amazon-pay-checkout/get-set-up-for-integration.html#nodejstab
I'd also recommend using the developer scratchpad as a way to sanity check your work and get tips on required code, since it will make requests for you and generate code snippets!
https://pay-api.amazon.com/tools/scratchpad/index.html
You can invoke the getCheckoutSession method from the SDK (.NET, Java, Node.js, PHP). The curl example that Amazon provides is only if you are developing a solution without using the SDK.
Here is an example from the Node.js SDK README.md.
npm i #amazonpay/amazon-pay-api-sdk-nodejs
const fs = require('fs');
const uuidv4 = require('uuid/v4');
const Client = require('#amazonpay/amazon-pay-api-sdk-nodejs');
const config = {
publicKeyId: 'ABC123DEF456XYZ',
privateKey: fs.readFileSync('path/to/private-key/private.pem'),
region: 'us',
sandbox: true
};
const headers = {
'x-amz-pay-idempotency-key': uuidv4().toString().replace(/-/g, '')
};
const checkoutSessionId = 00000000-0000-0000-0000-000000000000;
const testPayClient = new Client.WebStoreClient(config);
testPayClient.getCheckoutSession(checkoutSessionId, headers).then((apiResponse) => {
const response = apiResponse;
});

Generate OAuth 2.0 Access Token For PUT Request In Google Sheets API In JavaScript

GOAL
I would like to update some information in a Google Sheets document though a web service. I don't mind if the data is public, but it seems like I need to get an OAuth token in order to use PUT https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{range}as opposed to simply getting the data. However, I get back errors stating that I'm missing OAuth 2.0 credentials.
EXPECTATIONS
In order to do this, I assume that I need to first get credentials from Google's Developer Console . I currently have an OAuth 2.0 client ID and API key through that console. The API key is used to read the data and the OAuth would be used to write data.
I then need to hit an endpoint of some kind with the OAuth information to get credentials that'll be used. I'm supposed to put this info into my PUT request. This is the documentation I've found in regards to my request, but it's missing the authorization documentation.
QUESTIONS
1) Where is the endpoint that I'm hitting to get a refresh token and access token in Google's OAuth 2.0 stuffs? I've heard it's something like https://accounts.google.com/o/oauth2/token, but I'm not sure how to get the tokens. What do I need to pass? How do I pass that info? I can't find any documentation over it.
2) After getting these tokens, how do I incorporate them into the PUT request to the Google Sheets API? Do the tokens go into the Authorization header or the access_token query parameter or something?
I would highly recommend to check the Javascript Quickstart for Sheets API first as it includes OAuth sign-in demo.
From the quickstart code, this is the part that calls the OAuth library:
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
And here's me using the PUT request in an app I made:
function recordTimeInSheet(){
var params = {
"range":"Sheet1!"+A+":"+C,
"majorDimension": "ROWS",
"values": [
["bruceWayne","8:00AM", "5:00PM"]
],
}
var xhr = new XMLHttpRequest();
xhr.open('PUT', 'https://sheets.googleapis.com/v4/spreadsheets/'+myspreadsheetId+'/'+"values/"+"Sheet1!"+A+":"+C+"?"+'valueInputOption=USER_ENTERED');
xhr.setRequestHeader('Authorization', 'Bearer ' + myAccessToken);
xhr.send(JSON.stringify(params));
}

Get post response as json

Before I start, I'd like to say sorry for my English, it's not my native language.
I'm trying to setup OAuth2 for GitHub authorization.
I stucked at the step, where I should send POST request to github and receive access token. The problem is that when I send POST request my browser automatically downloads file with access token. Since I can't open this file with javascript, I'm trying to get json as response.
In the documentation it's written that I can change accept header and receive json, but I can't write correct POST request.
I've already tried a lot of things, like this:
$.ajax({
method: "POST",
url: "https://github.com/login/oauth/access_token",
dataType: "application/json"
});
or
$.ajax({
url: 'https://github.com/login/oauth/access_token',
headers: {
Accept : "application/json",
}
data: "data",
success : function(response) {
console.log(response);
} })
etc
But I get this error:
XMLHttpRequest cannot load github.com/login/oauth/access_token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://braga.fedyunin.com.ua' is therefore not allowed access. The response had HTTP status code 404.
Can't find any useful information in google, so I had to register here. Thanks for help.
Read https://developer.github.com/v3/ in section: Cross Origin Resource Sharing
I tried the same thing, but also failed due to the lack of the Access-Control-Allow-Origin header in the response from GitHub API. I contacted GitHub support and found out what was going wrong.
It doesn't work because you are attempting to use OAuth from a web application, which GitHub API does not support. When you authenticate this way, your client_id and client_secret must be in the web page somewhere and sent with the POST request. The entire request, including your client_secret, can be viewed with Firebug or a similar tool. Because it's a bad idea to expose your client_secret, GitHub API will not return the Access-Control-Allow-Origin header, thus preventing you from retrieving the token.
You must issue the POST from the server side and get the token that way. When you do that, the client_secret is on your server, not in people's browsers.
The Ajax request from your site to github.com fails because browsers follow the same origin policy for xhr requests. This means that an xhr request can only be made for a resource on the same origin.
To allow for cross origin requests, the server needs to Whitlelist domains that can access a particular resource.
In your case, to do this, you need to register your site as an application on your github account, by entering the details here:https://github.com/settings/applications/new

Do I have to make a script to make an authorization header for jwt?

I am working on a simple website using jwt. (node.js, koa.js)
Most example codes including expressjs, I cannot find the client-side example
about how to deal with jwt sent from a server.
Only one example (https://github.com/auth0-blog/cookie-jwt-auth) showed me that
[index.html]
... script src="app.js...
[app.js]
$.ajax({
type: 'POST',
url: 'http://localhost:3001/secured/authorize-cookie',
data: {
token: token
},
headers: {
'Authorization' : 'Bearer ' + token
}
After I read this example, I felt that I should have some scripts for users to send an authorization header with jwt. Is it right?
Or are there some front-end frameworks that deal with authorization header?
Thank you for reading newbie'q question.
Yes, you will need to define a mechanism for sending the user's JWT back to the server. It's up to you to decide where the JWT will live in the request -- the most common places are in the Authorization header, or by setting a cookie on the browser (which will be sent along with every HTTP request). You should also consider whether you want the JWT to persist across sessions / page reloads (using for example document.cookie or localStorage).
If you choose not to use the cookie approach, you can configure all $.ajax requests to set your Authorization header "pre-flight" using $.ajaxSetup({...}) (but this is a bit of a sledge-hammer approach). Manually setting the Authorization header on each individual $.ajax request, as you've demonstrated above, is a good option too.
If you want to skip headers all together, you can send the JWT inside the body of your request (as JSON, for example).

How to download large files from secure server with angularJS without storing whole file in browser? [duplicate]

I'm developing an single-page with Javascript+AngularJS on the client side and Spring MVC + Spring Security OAuth2 on the server side. Spring MVC acts as a REST controller for any AJAX requests from the page.
For authorization, the script sends an "Authorization: Bearer ..." headers with each AJAX request. This works fine when requesting small amounts of data.
To download XML files (export user data) I download them via AJAX, using the OAuth2 headers and create a Blob to allow saving the file in the browser:
var blob = new Blob([data.data], {'type': "text/xml"});
var a = document.createElement("a");
a.href = window.URL.createObjectURL(blob);
a.download = "downloaded-file-" + new Date().toISOString() + ".xml";
a.click();
This approach works but
Uses RAM and so is unsuitable for large file downloads
Does not show a proper progress/loading bar
So, the question is: is there a better way of downloading files with OAuth2 authorization? Javascript does not allow to specify headers when doing redirects, and OAuth does not allow to specify the authorization token via URL parameters. I'm thinking of either
adding a special Spring MVC controller method to provide an URL which redirects from an URL-encoded token to a header-encoded HTTP request
adding an extra Spring Security filter to allows extracting the token from URL parameters
moving to cookie-based authorization instead of OAuth2
If anyone had similar issues, could you please share your approach to this problem?
I would go with cookies if I were you - it takes all the hassle out of it. I wrote some blogs recently to show how easy it is (e.g. https://spring.io/blog/2015/01/20/the-resource-server-angular-js-and-spring-security-part-iii). People get too hung up on "stateless" applications.
Turns out it's very easy to to in spring-security-oauth2 2.0.7.RELEASE:
Simply pass the access token as the access_token request parameter:
window.open("service/export?access_token=" + access_token);
Now, this will appear with the access token in plaintext in the download history, so for proper security a "logout" option should be properly implemented, or the download will have to be done as a "form post".

Categories

Resources