I am trying to call fetch with credentials to hit a https api
url: https://{apikey}:{password}#{hostname}/admin/api/{version}/{resource}.json
I try this:
var apikey = "mykey";
var password = "mypass";
var hostname = "myhost";
var version = "version";
var resource = "resource";
var API_URL = `https://${apikey}:${password}#${hostname}/admin/api/${version}/${resource}.json`;
fetch(API_URL, {
credentials: "omit"
})
.then((response) => response.json())
.then((data) => console.log(data));
but return this error:
Failed to execute 'fetch' on 'Window': Request cannot be constructed from a URL that includes credentials
Just send credential with Header Authorization Bearer or Basic with base64 encoded credentials
Related
I'm trying to render the thumbnailLink image returned from the Google Drive API's /files endpoint. I'm doing this in an app running from localhost.
The docs mention this:
If the file isn't shared publicly, the URL returned in Files.thumbnailLink must be fetched using a credentialed request.
How do I build this "credentialed request"? I tried:
Adding my OAuth access token as an access_token query parameter. This gives me a 403 response (same as without the access_token param).
fetch()ing the image as a blob with the header { Authorization: 'Bearer ' + accessToken }. This request fails with a CORS error.
My OAuth access token has the following scopes:
https://www.googleapis.com/auth/drive.readonly
https://www.googleapis.com/auth/userinfo.email
EDIT: Minimal examples:
// This gives me a 403 response
function ThumbnailUsingUrl({ thumbnailLink }) {
const thumbnailUrl = new URL(thumbnailLink);
const searchParams = new URLSearchParams(thumbnailUrl.search);
searchParams.set("access_token", "my_access_token");
thumbnailUrl.search = searchParams.toString();
return <img src={thumbnailUrl.toString()} />;
}
// This gives me a CORS error
function ThumbnailUsingBlob({ thumbnailLink }) {
const [blob, setBlob] = useState(null);
useEffect(() => {
(async () => {
const response = await fetch(thumbnailLink, {
headers: {
Authorization: `Bearer <my_access_token>`,
},
});
setBlob(await response.blob());
})();
}, []);
if (!blob) return null;
return <img src={URL.createObjectURL(blob)} />;
}
I have been trying to retreive the access token for the paylocity API. I am able to get it through postman with the client id and client secret however when I try and retrieve it with Node.js I get the message {"error":"invalid_client"}.
Here is my code
const apikey = {user name};
const secret = {password};
const url = "https://api.paylocity.com/IdentityServer/connect/token";
const authorizationTokenInBase64 = Buffer.from(
`${apiKey}:${secret}`
).toString("base64");
const body = "grant_type=client_credentials&scope=WebLinkAPI";
let config = {
headers: {
Authorization: `Basic ${authorizationTokenInBase64}`,
"Content-Type": `application/x-www-form-urlencoded`,
},
};
try {
const response = await axios.post(url, body, config);
} catch (error) {
console.log("error", error.response.data);
}
I need to get access token from SharePoint, In order to upload some files!
I got access token from postman successfully, But when I try to do the same request with Javascript!
const generateToken = async () => {
const headers = { "Content-Type": "application/x-www-form-urlencoded" };
var formdata = {};
formdata["grant_type"] = "client_credentials";
formdata["client_id"] = "<client_id>";
formdata["client_secret"] = "<client_secret>";
formdata["resource"] =
"00000003-0000-0ff1-ce00-000000000000/site_url#tenant_id";
const body = Object.keys(formdata)
.map((key) => `${key}=${formdata[key]}`)
.join("&");
var requestOptions = {
method: "POST",
headers,
body,
};
await fetch(
"https://accounts.accesscontrol.windows.net/<tenant_id>/tokens/OAuth/2",
requestOptions
)
.then((response) => response.json())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
};
generateToken();
when I execute the page which have this script I got this error
error TypeError: Failed to fetch
at generateToken
But IDK why the respose status is 200 OK, without returning body which contain access_token
Any help is much appreciated!
You cannot get the token from javascript like that, only from single page applications because of the security issues: you expose your client secret.
You can use Microsoft Authentication Library (MSAL) for JS instead.
I am attempting to fetch a php app hosted on AWS with basic authentication. I followed tutorials and attempted other answers such as encrypting the username and password using btoa
Currently, this is my code:
let h = new Headers();
let url = "URL"
let user = "USER"
let pass = "PASS"
let encoded = window.btoa(`${user}:${pass}` )
let auth = ('Basic ' + encoded)
console.log(auth)
h.append('Authorization', auth)
console.log(h.has('Authorization'))
fetch(url, {
headers: h
}) .then(res => console.log(res))
Thanks in advance!
I'm using the Fetch API to Login to my Webapp using Baisc Authentication. After a successful login the server returns a token as a json object. I am then using this token to make requests to other API Endpoints. Those endpoints just show a webpage if the request contains a valid token.
Everything works fine but nothing shows up in the browser after I make a successful call with the fetch API..
If I call the API endpoint in a REST Client it returns the html which seems to be fine. The problem seems to be that the browser should call the url instead of just fetch the html..
Here is my code. I am getting the "Success"-Alert - so everything seems to work fine. But I need the browser to show the result as a new page (some kind of a direct call of the url with the token in the header).
function login(event) {
event.preventDefault();
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let url = URL + 'login';
let headers = new Headers();
headers.append('Authorization', 'Basic ' + btoa(username + ":" + password));
fetch(url, {method:'GET',
headers: headers,
})
.then(function(response)
{
if (response.ok) {
return response.json();
} else {
let error = document.getElementById("login-error");
error.innerHTML = "Username/Password incorrect.";
}
})
.then(function(json)
{
if (typeof(json) !== "undefined") {
startWebapp(json.token);
}
})
.catch(error => console.error('Error:', error));
}
function startWebapp(token) {
let url = URL + 'webapp/overview';
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + token);
fetch(url, {method:'GET',
headers: headers,
})
.then(function(response) {
alert("Success!");
return response;
});
}
How can I achieve that the browser actually calls the url with the API token and opens it if the fetch is successful?
For anyone searching for a solution:
This is actually not possible with JavaScript nor the fetch API. For me the (easiest) solution is to save the token in a cookie. The server then searches for a token in the cookie and uses it for authentication/authorization. This works pretty well and I don't need to send the token on every request.
Hope that helps.