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!
Related
I am trying to send SMS through my web app, I bought bulk SMS from SMS supplier, trying to engage with their api.thanks in advance for your help
I post the data through postman and it works (post method, headers section), when I post data from my webpage to their URL it doesn't work,
$(document).ready(function() {
// Add event listener for opening and closing details
$('#testbut').on('click', function() {
var Username = 'xxxxxx';
var password = 'xxxxx';
var language = '1';
var sender = 'RitaFoods';
var Mobile = '2011xxxxx';
var message = 'hello from the other side';
$.ajax({
url: "https://smsmisr.com/api/webapi/?",
method: "POST",
"headers",
data: {
Username: Username,
password: password,
language: language,
sender: sender,
Mobile: Mobile,
message: message
},
dataType: "JSON",
success: function(data) {
alert("done");
alert(JSON.stringify(data));;
}
})
});
});
when I sending this data to another page on my web site, I received it with no problem , and i response with the parameters and alert it, when I sending to api url it gives no response, maybe because I need to send in headers section but I don't know how to do this.
You can set header with the beforeSend function
$.ajax({
url: "https://smsmisr.com/api/webapi/?",
method: "POST",
data: {
Username: Username,
password: password,
language: language,
sender: sender,
Mobile: Mobile,
message: message
},
beforeSend: function(xhr){xhr.setRequestHeader('My-Custom-Header', 'My-Value');},
dataType: "JSON",
success: function (data) {
alert("done");
alert(JSON.stringify(data));;
}
});
or via the headers field
$.ajax({
url: "https://smsmisr.com/api/webapi/?",
method: "POST", "headers",
data: {
Username: Username,
password: password,
language: language,
sender: sender,
Mobile: Mobile,
message: message
},
headers: {
'My-Custom-Header': 'My-Value',
},
dataType: "JSON",
success: function (data) {
alert("done");
alert(JSON.stringify(data));;
}
});
Look at the API documentation.
It says "Post in header not in body", but as a description of what you need to do, this is wrong.
Look at the examples. They show that the data is encoded in the query string of the URL. In HTTP terms, that means it goes in the start line, not a header.
So you need to do something like:
var url = new URL("https://smsmisr.com/api/webapi/?");
url.searchParams.append("Username", Username);
url.searchParams.append("Password", password);
// etc etc
$.ajax({
url: url,
method: "POST",
dataType: "JSON",
success: function(data) {
alert("done");
alert(JSON.stringify(data));;
}
})
See this answer if you need compatibility with older browsers.
Be warned that you are likely to run into the problem described in this question.
try to add in your ajax
contentType: "application/json"
$.ajax({
type: "POST",
url: **your URL**,
data: **your DATA**,
contentType: "application/json",
});
I have next situation:
Main authentication flow happens on server, then client side obtains these data, since that moment I wanna client be able to update token by itself. It's seems there is all needed data on client(access_token, refresh_token), but I can't figure out how to organize request to https://login.microsoftonline.com/common/oauth2/v2.0/token route.
First I tried to get json response:
$.ajax({
url: `https://login.microsoftonline.com/common/oauth2/token?grant_type=refresh_token&refresh_token=refresh_token&scope=openid%20profile%20offline%20access%20user.read%20mail.read%20contacts.read%20calendars.read&client_id=client&client_secret=secret`,
type: 'POST',
cache: false,
processData: false,
contentType: false,
dataType: 'json',
headers: {
'Host': 'https://login.microsoftonline.com',
'Content-Type': 'application/json'
},
success: function(data) {
...
},
error: function(xhr) {
...
}
});
After that I figured out that it's only possible to get this data with redirect, is it correct? If it is, can someone produce an example of how to implement this, looks like it's needed to create an iframe and handle authorization somehow. Thanks.
UPDATED:
as Alina Li pointed in comment to her answer, there is a solution right in the official doc https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
According to my test, you could using refresh-token through the below code:
var data = "grant_type=refresh_token&refresh_token=refreshToken&client_id=" + appState.clientId;
$http = $http || $injector.get('$http');
$http.post(authUrl + '/token', data, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (response) {
}).error(function (err, status) {
});
You don’t need to add scope parameter.
Reference from:
Storing Refresh Token In JavaScript, Getting New Access Token
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.
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);
}});
I am trying to use the JIRA REST API to preform some requests. One of the first things that you must do, according the docs, is authenticate in some way.
Atlassian offers 2 methods; Basic Auth and Cookie Based Auth, the later of which uses cookies to establish a session.
The issue comes into play when I involve Jquery/JS.
Here is the request when preformed in ARC (Advanced Rest Client) for Chrome:
If I run that request, I will get a HTTP 200 response with the correct JSON, which is what I want.
However, when I attempt to do this with Jquery/JS, I recieve an error every time.
Here is that code:
function cookieLogin() {
//Grab username and password from the fields on the page
var user = $("#loginUsername").val();
var pass = $("#loginPassword").val();
$.ajax({
//URL
url: baseURL + path,
//Method
//type: 'POST', //analogous to 'method'
method: 'POST',
//Headers
accept: 'application/json',
dataType: 'application/json',
contentType: 'application/json',
//Payload to be sent
data:
{
"username": "admin",
"password": "admin"
},
//Responses to HTTP status codes
statusCode: {
200: function () {
alert("Success!");
},
401: function() {
alert("Invalid Credentials");
},
403: function () {
alert("Failed due to CAPTCHA requirement/throttling.")
}
},
success: function (data) {
var result = jQuery.parseJSON(data);
console.log(result);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error!!!");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
I have assured that the URL is correct. As you can see, I also hard-coded the credentials (this is merely a test page) just to test as well. I'm not sure why I am receiving errors in JS when I replicated the same thing that worked in ARC.
As per the documentation, I am seeing that "accept" should be "accepts" and "dataType" takes the string "json", not "application/json".