How to use UrlFetchApp with credentials? Google Scripts - authentication

I am trying to use Google Scripts UrlFetchApp to access a website with a basic username and password. As soon as I connect to the site a popup appears that requires authentication. I know the Login and Password, however I do not know how to pass them within the UrlFetchApp.
var response = UrlFetchApp.fetch("htp://00.000.000.000:0000/‎");
Logger.log(response.getContentText("UTF-8"));
Currently running that code returns "Access Denied". The above code does not contain the actual address I am connecting to for security reasons. A "t" is missing from all the "http" in the code examples because they are being detected as links and Stackoverflow does not allow me to submit more than two links.
How can I pass the Login and Password along with my request? Also is there anyway I can continue my session once I have logged in? Or will my next UrlFetchApp request be sent from another Google server requiring me to login again?
The goal here is to login to the website behind Googles network infrastructure so it can act as a proxy then I need to issue another UrlFetchApp request to the same address that would look something like this:
var response = UrlFetchApp.fetch("htp://00.000.000.000:0000/vuze/rpc?json={"method":"torrent-add","arguments":{"filename":"htp://vodo.net/media/torrents/anything.torrent","download-dir":"C:\\temp"}}‎");
Logger.log(response.getContentText("UTF-8"));

This question has been answered on another else where.
Here is the summary:
Bruce Mcpherson
basic authentication looks like this...
var options = {};
options.headers = {"Authorization": "Basic " + Utilities.base64Encode(username + ":" + password)};
Lenny Cunningham
//Added Basic Authorization//////////////////////////////////////////////////////////////////////////////////////////
var USERNAME = PropertiesService.getScriptProperties().getProperty('username');
var PASSWORD = PropertiesService.getScriptProperties().getProperty('password');
var url = PropertiesService.getScriptProperties().getProperty('url');//////////////////////////Forwarded
Ports to WebRelay
var headers = {
"Authorization" : "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD)
};
var params = {
"method":"GET",
"headers":headers
};
var reponse = UrlFetchApp.fetch(url, params);

I was unable to find user3586062's source links (they may have been deleted), but taking Bruce Mcpherson's approach, your code would look like this:
var options = {};
options.headers = {"Authorization": "Basic " + Utilities.base64Encode(username + ":" + password)};
UrlFetchApp.fetch("TARGET URL GOES HERE", options);

Related

Getting A Refresh Token From Google Using An Authorization Token Posted in Java

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.

403 access denied to the website with proper login/pass through google script

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.

Monzo API: Invalid request: required parameter client_id is unknown

I keep getting the following error Invalid request: required parameter client_id is unknown when making a request to the monzo auth api to get an access token. I am getting the client_id from the developer playground response using GET /ping/whoami.
I am then putting this into my request:
let clientID = "oauthclient_XXXXXXXXXXXXXXXX"
let baseURL = "https://auth.monzo.com/"
let redirectURI = "https://Monzo-AR.novoda.com"
let responseType = "code"
let stateToken = "random string"
var requestURL: String!
requestURL = baseURL +
"?client_id=" +
clientID +
"&redirect_uri=" +
redirectURI +
"&response_type=" +
responseType +
"&state=" +
stateToken
Can anyone see what i am doing wrong?
The /ping/whoami endpoint returns the client_id for the Developer Console (which was used to authenticate you for that service)
It's not suggested to use that client_id in your own applications. If you head to the Monzo Clients Page you will be able to create your own client and receive an ID for it.
Additionally, the redirect URI must match that of the one configured in the clients page linked before (You will get an error otherwise)
You haven't given context to what you're doing with the requestURL - You will need to redirect the user to this page in order to authenticate.
Once you have been redirected to the authentication page at the link you've constructed, you'll be able to use your browsers console (Cmd + Option + J on Chrome Mac) to see any errors that present themselves

How do I authenticate, using Nim's httpclient module to retrieve HTML?

I'm a beginner and I want to write a Nim-application that processes some data from an internal website.
Basic authentication (username, password) is required to access this site.
A working Python solution is:
response = requests.get('https://internal:PORT/page',
auth=('user', 'passwd'),
verify=False) # this is vital
Based on the nim doc regarding httpclient and the modules source code, where it is stated that one could use a proxy as an argument for any of the functions, I've been trying something along these lines:
var
client = newHttpClient()
prox = newProxy("https://internal:PORT/page", "user:passwd")
let response = client.getContent(prox) # Error: type mismatch
The solution is probably very obvious but I'm out of ideas on
how to authenticate.
If anybody could help, that'd be highly appreciated!
Basic auth is just an "Authorization" header with value "Basic " + base64(username + ":" + password). Equivalent in nim:
import httpclient, base64
var
client = newHttpClient()
var username = ...
var password = ...
client.headers["Authorization"] = "Basic " & base64.encode(username & ":" & password)
# ... send request with the client

cordova/phonegap 3.3: how to set user credentials in fileUploadOptions

I'm trying to make a file upload via Phonegap 3.3 file transfer plugin to a windows server secured by base authentication. Actually the normal conversation between my app and the server (per ajax) is working perfectly by sending my user credentials with every ajax call.
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
options.headers = {
'Authorization':authHeaderValue(db.getItem("user"), db.getItem("pass"))
};
and
authHeaderValue = function(username, password) {
var tok = username + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
};
This is what I tried so far (I found it on stackoverflow thread) but it gives me back a 401-unauthorized...
Pls. give me a short reply if you know something that could help me.
Best regards to you all,
Ingmar
Well, I do something similar but instead of "Basic" I use JWT for authentication. I'll show you the code I use:
options.headers = { 'Authorization': 'Bearer ' + app.session.getSess('token') };
And I use SessionStorage to save the token while it is valid.
If you wanna know about JSON Web Token
Another thing, remember to change the headers in your server, in my case something like:
('Access-Control-Allow-Origin','*');
('Access-Control-Allow-Methods','GET,PUT,POST,DELETE,OPTIONS');
('Access-Control-Allow-Headers','Content-Type, Authorization, Content-Length, X-Requested-With');