In JScript I need to read a list of books from a web server that has a 2-step authentication i.e. user + password and token afterwards - once you call an IP address you get a token in response which needs to be used in a header for books (Authorization; Bearer + token). Server is supposed to respond with a paginated list of books
[{"book_Id": 1,"book_Name": "AAA","book_Year": 2021}].
Path is "GET /book", parameters are: "Page" and "Size". I've managed to call the server and get token in reponse:
var xmlhttp = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
xmlhttp.open("GET", "http://XX.XX.XX.XX:XXXX/authenticate?username=XXX&password=XXX", false);
xmlhttp.send();
var token = JSON.parse(xmlhttp.responseText).token
and tried to use it
var header = xmlhttp.SetRequestHeader("Authorization", "Bearer "+token)
new ActiveXObject("WScript.Shell").Popup(header.responseText)
but got empty response and got stuck. I'd very much appreciate being moved on with how to read the list.
Edit
So I've added new object and now get status 404 error Not Found. Is there some error in the coding yet?
var xmlhttp = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
xmlhttp.open("GET", "http://XX.XX.XX.XX:XXXX/authenticate?
username=XXX&password=XXX", false);
xmlhttp.send();
var token = JSON.parse(xmlhttp.responseText).token
var xmlhttp2 = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
xmlhttp2.open("GET", "http://XX.XX.XX.XX:XXXX/book?limit=1", false);
xmlhttp2.SetRequestHeader("Authorization", "Bearer "+token)
xmlhttp2.send();
new ActiveXObject("WScript.Shell").Popup(xmlhttp2.responseText)
Related
I have read many posts, all the Google documentation I can find and tried many iterations of the following and still can't get an access and refresh token. I do get an authorization code but can't seem to get that to trade for the access and refresh tokens.
if(authCode == null || authCode.equals("")) {
String url = "https://accounts.google.com/o/oauth2/v2/auth?"
+ "scope=https://mail.google.com/&"
+ "response_type=code&"
+ "redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&"
+ "client_id=" + clientId +
"&access_type=offline";
URI uri = new URI(url);
logger.debug("URI for auth is: " + uri);
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(uri);
}
}
else {
logger.debug("Refreshing");
initRefreshToken();
}
With that, I get an access code I can cut and paste (just testing and trying to get this to work first) in my properties to get the refresh and access token.
In the initRefreshToken() method, the source is like this:
if(refreshToken.equals("")) {
logger.debug("Getting refresh token");
HttpPost post = new HttpPost("https://oauth2.googleapis.com/token");
// add request parameter, form parameters
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("code", authCode));
urlParameters.add(new BasicNameValuePair("client_id", clientId));
urlParameters.add(new BasicNameValuePair("client_secret", clientSecret));
urlParameters.add(new BasicNameValuePair("redirect_uri", "http://localhost:8000/"));
urlParameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
try {
post.setEntity(new UrlEncodedFormEntity(urlParameters));
System.out.println("***** URL: " + urlParameters);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post);
System.out.println(EntityUtils.toString(response.getEntity()));
}
If this is a second or subsequent time using the code, what will be printed is:
Refersh token:
***** URL: [code=4/1AY0e-g..., client_id=370...i1h2u1s.apps.googleusercontent.com, client_secret=bAOH..., redirect_uri=https://localhost:8000/, grant_type=authorization_code]
{
"error": "invalid_grant",
"error_description": "Bad Request"
}
If the code is run and it's the first time using an authentication code, it will print:
{
"error": "redirect_uri_mismatch",
"error_description": "Bad Request"
}
I read in the Google console that exceptions are made for localhost domains so there's no need to register them. However, if there were a need to register them, it won't let you register them anyway as a domain must be a top level domain you own in order to register it. Therefore, how do I register localhost and/or exchange an authorization code for an access and refresh token in Java?
Thank you for your help.
DaImTo provided a great video about this and in that video and the blog post associated with it, the redirect_uri is listed correctly as: "urn:ietf:wg:oauth:2.0:oob". I didn't find this in the documentation but when I added it to my source code, I got access and refresh tokens as a response. Thank you very much for that help, DaImTo.
var url = "https://web-site_name/page/?format=json&var_data-organization_dates&xlsexport=true";
var payload =
{
"login" : "login",
"password" : "pass",
};
var options =
{
"method" : "post",
"payload" : payload,
"followRedirects" : false
};
var login = UrlFetchApp.fetch("https://web-site_name/page/" , options);
var sessionDetails = login.getAllHeaders()['Set-Cookie'];
Logger.log(login.getAllHeaders());
here is the part of the code I try to use, to automate export of the data from web-site, i do have proper login and password and able to download file in json (opened in xsl) manually, I've got the address to the downloaded file in network in developer tools, but i have a problem on the first stage - when trying to authorize to the web-site - access denied. I've tried the code, given in answers on stackoverflow, but it still doesn't work.
How to make an url fetch request correctly, depends on the website you want to access and the authentication they uses
In the simplest case, your website requires HTTP basic authentification, in this case the correct syntax would be
var authHeader = 'Basic ' + Utilities.base64Encode(login + ':' + pass);
var options = {
headers: {Authorization: authHeader}
}
If your website uses a different authentication form, you might need to provide an access token.
In any case: the authentication credentials go into headers, not into payload!
payload is the data that you want to post = upload to the website.
If you want export data from the website - that is download data - you do not need a payload and the correct method would be get, not post. Btw., if the method is get, you do not need to specify it.
Please see here for more information and samples.
I'm trying to debug another developers code which looks like this:
xhr.open("POST", url, true, this.state.userid, this.state.password);
xhr.withCredentials = true;
xhr.onload = () => {
console.log("here is our packet " + JSON.stringify(xhr));
if (xhr.status === 200) {
var test = xhr.getAllResponseHeaders();
var respoheader = JSON.stringify(xhr.responseHeaders);
var token = respoheader.substring(
respoheader.indexOf("LtpaToken2"),
respoheader.indexOf(
";",
respoheader.indexOf("LtpaToken2")
)
);
console.log("token is parsed ===" + token);
When I run this query from Postman I see two "Set-Cookie" headers added to the response, and one has the content "LtpaToken2=YpMnhu...", which is apparently what I need to grab. But when I run the code above, it does not include this header. I apparently need to grab this token for future calls to another API.
Can someone explain what I'm doing wrong? How can I capture this token, or how am I supposed to connect to another API without this token? As it seems to always be the case with IBM tech, I can find almost ZERO documentation about LtpaTokens.
I have a API GET call that works in postman BUT not in VS2017. I copied the code
from postman:
var client = new RestClient("http://server- d01:9000/amp/portal/api/dougtest/v1");
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "19763da3-4b00-4e92-83e0-1ac75f99d219");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("X-XSRF-TOKEN", "71cf12361-8090-499a-adc3-2d5e98a04143");
request.AddParameter("undefined", "{\n \"username\":\"domain\\\\username\",\n \"password\":\"myPasswd\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
The error I am getting is unauthorized, the API required a header of X-XSRF-TOKEN with a value of 71cf12361-8090-499a-adc3-2d5e98a04143 (a fake key)
Using postman, everything works just fine, but using VS2017 I get an error:
{"status":"unauthorized","error":"Login is required","errormsg":null}
What's weird (I am new to this so pardon my ignorance)is that the header does not contain:
request.AddHeader("X-XSRF-TOKEN", "71cf12361-8090-499a-adc3-2d5e98a04143");
but rather the parameter does, which is confusing since I thought the AddHeader would add it to the header but maybe I am misunderstanding something....
any advice/suggestions would be extremely welcomed
thank you in advance
dougc
Please use the below code and check
var client = new RestClient("http://server- d01:9000/amp/portal/api/dougtest/v1");
var request = new RestRequest(Method.GET);
//Make sure to give the Valid Token
request.AddHeader("Authorization","X-XSRF-TOKEN <<Generated Token>>");
IRestResponse response = client.Execute(request);
Console.WriteLine("Response :" + response.Content);
I've downloaded a exampled that show the files in the "Shared with everyone" folder in my OneDrive for Bussiness. It's work fine!
But, when I try to create a Folder or File (without content) like this documentation the response became with a BadRequest .
The request goes like:
string requestUrl = String.Format(CultureInfo.InvariantCulture, "{0}/files", serviceInfo.ApiEndpoint);
// Prepare the HTTP request:
using (HttpClient client = new HttpClient())
{
Func<HttpRequestMessage> requestCreator = () =>
{
HttpRequestMessage request = new HttpRequestMessage( HttpMethod.Post, requestUrl);
request.Headers.Add("Accept", "application/json;odata.metadata=full");
request.Content = new StringContent(#"{'__metadata':{'type':'MS.FileServices.Folder'},Name:'TestFolder'}");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return request;
};
}
And the response is a BadRequest.
I think that my problem is in the "__metadata"'s json value. It´s is correct? Where can I find a working example implementing this operations?
Thanks in advance!
EDIT: Changing the API Endpoint from "/_api/web/getfolderbyserverrelativeurl('Documents')/files" to "_api/files" the error became to: "The property '__metadata' does not exist on type 'MS.FileServices.FileSystemItem'. Make sure to only use property names that are defined by the type."
I´m think I foward in this. But, I still continue with problems.
I am not sure if this can be of any help to you, as this pertains to oneDrive and not oneDrive for business.
Also the documentations are confusing :)
according to the documentation the request should be as follow:
POST https://apis.live.net/v5.0/me/skydrive
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json
{
"name": "My example folder"
}
if you can see that in the header there is authorization access token
I don't see that you sent to the server any access token. and that is why you had a bad request.
I am trying to below way to create a folder in SP and it's working for me. Hope it will work for you as well.
Create a folder using SharePoint Web API -
POST https://<Domain>.sharepoint.com/_api/web/folders
Accept: "application/json;odata=verbose"
Content-Type: "application/json"
{
"ServerRelativeUrl": "/Shared Documents/<Folder-Name>"
}