Sending custom headers required to load a page - javascript

I have a webpage that requires an id and a token to be sent in the header for the page to load. A php login script returns the id and token. Then this id and token needs to be sent in the header of the page for it to load. Check is provided to look for these custom header, if not set, it is redirected to the login page. The page needs to be loaded from a javascript function. If I use window.location, it is redirected to the login page as the headers are not found. How do I achieve this?
Here is my code:
$.ajax({
type: "POST",
url: "http://www.example.com/apis/login.php",
data: JSON.stringify(inputs),
dataType: "json",
success: function(data) {
if(data.status == "success") {
username = data.username;
uid = data.uid;
token = decodeURIComponent(data.token);
loadpanel(username, uid, token);
}
else{
alert(data.message);
}
},
error: function() {
alert("could not connect to server");
}
});
function loadpanel(username, uid, token) {
$.ajax({
async: true,
type: "GET",
url: "/haspanel.php",
headers: {
"U-Name" : username,
"U-Id" : uid,
"Auth-Token" : encodeURIComponent(token)
},
success: function(data) {
window.location='/haspanel.php';
},
error: function() {
alert("could not connect to server");
}
});
}
I know, this won't work, but I don't understand what is the workaround.

You could just do this right? :
window.location = '/page.php?id='+ id +'&token='+ token +'';
Where id and token are variables that contain the required values of your id and variable parameters.

Related

csrf token is changing where it shouldn't be changed

I'm running code below to prevent CSRF vulnerability
if (!isset($_POST['_token'])) {
$_SESSION['_token'] = bin2hex(random_bytes(20));
}
and i am using the token in hidden inputs named _token. I use the following code in my main.js file so that the user can add the product to their favorites.
const wishlist = {
'add': function (id) {
$.ajax({
url: 'api/wishlist?method=add',
type: 'post',
dataType: 'json',
data: 'id=' + id + '&_token=' + $('input[name="_token"]').val(),
success: function (response) {
console.log(response)
}
})
},
'remove': function (id) {
$.ajax({
url: 'api/wishlist?method=remove',
type: 'post',
dataType: 'json',
data: id,
success: function (response) {
console.log(response)
}
})
}
};
Below is the code in wishlist.php which ajax request goes to
<?php
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
header('Location:' . site_url('404'));
}
if (!isset($_POST['_token']) or $_POST['_token'] != $_SESSION['_token']) {
die('Invalıd CSRF Token!');
}
if ($_GET['method'] == 'add') {
$json['method'] = "adding to favorites";
}
if ($_GET['method'] == 'remove') {
$json['method'] = "removeing from favorites";
}
The all code is this but sometimes this code works sometimes it gives Invalid csrf token error and sometimes it works for 3-5 times and gives error again.
I found the solution. It was because client is trying to access to an non-exist file
so that that request executes init.php

How to make a REST API Request with Ajax and session token?

I'm having trouble following an API Guide using AJAX. I have successfully got the session token from the login api as the session token is needed to make requests to GET/POST data.
Code to get the session token:
var sessionToken = null;
$.ajax({
url: '<API-URL>/1/json/user_login/',
data: {
'login_name' : 'USERNAME',
'password' : 'PASSWORD'
},
type: 'GET',
dataType: 'json',
success: function(data) {
sessionToken = data.response.properties.session_token;
$("#result").text("Got the token: " + sessionToken);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
function setHeader(xhr) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
On successful, we get the session token: D67ABD0454EB49508EAB343EE11191CB4389255465
{response: {…}}
response:
properties:
action_name: "user_login"
data: [{…}]
action_value: "0"
description: ""
session_token: "D67ABD0454EB49508EAB343EE11191CB4389255465"
__proto__: Object
__proto__: Object
__proto__: Object
Now that I have a valid session token, I can now make requests to get data. I'm trying to get driver data using the following code:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
According to the documentation, I need to use POST instead of GET in order to get vehicle details in the response and pass the session token as a parameter:
Unfortunately it seems to return blank data when using GET and Permission denied when using POST. I've tried sending the parameters as an array like the documentation but that fails also. I've tried passing the session token as Authorisation but still get no response.
The only help I got from the API support team was: "POST can’t be with parameter query on the end point."
What am I doing wrong?
Any help is appreciated. Thanks!
I don't know what service/api you're trying to call, but from the error message you've posted and the brief documentation it looks like you're structuring your url wrong:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
You're including the action parameter as part of the url by the looks of things when the doc you posted implies it should be part of the data (and the error they sent you of "POST can’t be with parameter query on the end point." also supports this). So try the following: (of course without seeing more of the docs it's difficult to know if your actual base url is correct)
$.ajax({
url: '<API-URL>/1/json/',
data: {
'action': {'name':'api_get_data',
'parameters': [ {'license_nmbr' : vrn }],
'session_token' : sessionToken
}
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});

how to read token from header by js

I'm trying to read token from header by plain java script , so I have two pages
A page request B page by
var B = function(){
$.ajax({
url: 'b.html',
method:'get',
dataType: 'json',
success: function(data) {
//do some handle functions
},
error: function(error){
console.log(error);
},
beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization','Bearer ' + access_token ); }
});
}
so, now i want read Authorization access token in B page by javascript !
You can use the XMLHttpRequest.getAllResponseHeaders() method to find the token header and retrieve the response.
More Information can be found at : https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

Getting Pop up window to login with basic authentication using Ajax?

Here I am trying to access reed.co.uk rest webapi to fetch all related jobs, When I call the URL, its showing this popup window even though I am passing username and password. This is the alert message I am getting:
http://www.reed.co.uk is requesting your username and password.
WARNING: Your password will not be sent to the website you are
currently visiting!
Pls help me where i am doing wrong.
Here is the Ajax code
var username = "xxxxx xxxxxxxxxxxxxxx";
var password = "";
function getAuthorizationHeader(username, password) {
var authType;
var up = $.base64.encode(username + ":" + password);
authType = "Basic " + up;
console.log(authType);
return authType;
};
$.ajax({
type: "GET",
url: "http://www.reed.co.uk/api/1.0/search?keywords=Software Engineer&locationName=London&distanceFromLocation=50",
dataType: 'jsonp',
async: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', getAuthorizationHeader(username, password));
},
success: function (response) {
console.log(response);
}
});
I tried passing Authorization header like this also but still i am getting pop up window
headers: {
'Authorization': getAuthorizationHeader(username, password)
},
It looks like it is expecting Basic Authentication. Thus you need to supply it at url.
For example:
$.ajax({
type: "GET",
url: "http://"+username+":"+password+"#www.reed.co.uk/api/1.0/search?keywords=Software Engineer&locationName=London&distanceFromLocation=50",
dataType: 'jsonp',
async: false,
success: function (response) {
console.log(response);
}});

How to move to another page using Javascript and access token?

This problem must have been solved billions of times, yet I'm having a hard time finding my way. I have a backend service that grants OAuth2 tokens with user/password. When the user logs in, I would like the browser to go to the next page. The thing is, such page is only accessible with an auth header. Methods such as document.location.href = "http://nextpage" don't let me set the authorization header, like Authorization = Bearer 1234567890.
The code that runs when the user clicks on the "Login" button is:
var json = {
grant_type: "password",
client_id: "myClient",
username: email, // <--- comes from a form
password: password, // <--- comes from a form
client_secret: "mySecret"
};
$.ajax({
url: "http://localhost:9000/auth/token/grant",
method: 'POST',
contentType: "application/json",
dataType: 'json',
data: JSON.stringify(json),
cache: false,
success: function (data) {
localStorage.authToken = data.access_token;
localStorage.refreshToken = data.refresh_token;
// Here I would like to move the browser to the next page
document.location.href = "http://localhost:9000/nextPage";
}.bind(this),
error: function (xhr, status, err) {
console.error("login request error: ", status, err.toString());
}.bind(this)
});
Thanks for your tips!

Categories