I have an openIDM program and when users submit for update new password , it show "X-openIDM-Reauth-Password" which include my old password that i need to retype. Following is the screen shot from openidm side.
So, i have my own UI and i was request from javascript ajax side with following ajax call.
$.ajax({
contentType: "application/json; charset=UTF-8",
datatype: 'json',
url: targetHost+"openidm/managed/user/"+userId,
xhrFields: {
withCredentials: true,
},
headers: {
"X-Requested-With":"XMLHttpRequest" ,
"X-OpenIDM-Reauth-Password": oldPassword
},
crossDomain:true,
data: JSON.stringify(data),
type: 'PATCH',
success:function(result) {
console.log("success");
swal({
title: updateSuccessMsgs.formSubmit.slogan,
text: updateSuccessMsgs.formSubmit.success,
type: "success"
}, function() {
window.location = "my-profile.html";
});
},
error:function (error){
sweetAlert(updateErrorMsgs.updateError.slogan, updateErrorMsgs.updateError.fail, "error");
console.log(error);
}
});
and it throw me this error.
XMLHttpRequest cannot load http://localhost:9090/openidm/managed/user/09096425-4ff1-42d4-8a4d-3a6b5004afca. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
Can someone explain me why? Appreciate it.
I found the solution. I try to add one more value in servletfilter-cors.json as follow. I added the value of "X-OpenIDM-Reauth-Password" in "allowedHeaders" and it is success.
{
"classPathURLs" : [ ],
"systemProperties" : { },
"requestAttributes" : { },
"scriptExtensions" : { },
"initParams" : {
"allowedOrigins" : "*",
"allowedMethods" : "GET,POST,PUT,DELETE,PATCH",
"allowedHeaders" : "accept,x-openidm-password,x-openidm-nosession,x-openidm-username,content-type,origin,X-OpenIDM-Reauth-Password,x-requested-with",
"allowCredentials" : "true",
"chainPreflight" : "false"
},
"urlPatterns" : [
"/*"
],
"filterClass" : "org.eclipse.jetty.servlets.CrossOriginFilter"
}
Related
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
});
I'm sending this request, and it is perfectly fine as long as it's successful. However, if I try to create a user with existing username or email, I should get 400 bad request and response detailing what's the problem.
Thing is, when I send this request and get 400, nothing gets written to console/console (not even the 'fail!' string), but I can see that response is correct in console/network tab so the problem is probably not in the backend.
$("#registerForm").submit(function(e){
e.preventDefault()
$.ajax({
type: "POST",
url: "./register",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
"username": formcontent['username'],
"email": formcontent['email'],
"password": formcontent['password'],
}),
success: function(e) {
window.location.href = './login'
return false
},
fail: function(e) {
console.log('fail!')
console.log(e)
//react to error
return false
},
})
})
I think 'fail' is a invalid function, Please try with below structure
$.ajax({
type : "POST",
url : "/register",
contentType : "application/json; charset=utf-8",
dataType : "json",
data : JSON.stringify({
"username" : formcontent['username'],
"email" : formcontent['email'],
"password" : formcontent['password'],
}),
success : function(response) {
console.log(response);
},
error : function(response, status, err) {
console.log(response);
console.log(status);
console.log(err);
}
});
I want to call an OAuth2 service with grant_type password.
I am using Backbone with Jquery.
Parameters for the POST:
grant_type=password
client_id=[YOUR_APP_ID]
client_secret=[YOUR_CLIENT_SECRET]
username=[USER_NAME]
password=[USER_PASSWORD]
I have tried several NPM plugins but all give error.
I have created a custom post AJAX but this also does not work:
var results = $.ajax({
// The URL to process the request
url : "https://app1pub.smappee.net/dev/v1/oauth2/token",
type : "POST",
data : {
grant_type : "password",//jshint ignore:line
username: "myuser",
password: "secret",
client_id: "myclient",//jshint ignore:line
client_secret: "clientSecret"//jshint ignore:line
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer $token");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
dataType: "json",
contentType: "application/x-www-form-urlencoded",
success: function(response) {
//console.log(response);
console.log(response.access_token);//jshint ignore:line
data.access_token = response.access_token;//jshint ignore:line
//tokenGranted();
}
});
return results.responseText;
(see fiddle: https://jsfiddle.net/gf70sss5/)
All give me the error:
"XMLHttpRequest cannot load https://app1pub.smappee.net/dev/v1/oauth2/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access."
Does anyone know a NPM plugin which works with the password granttype? Preferrably with an example. I have tried a few (like simple-oauth2) but I can't get any working.
Or an AJAX call which does work? Or what I am doing wrong?
Try this, but i've still a problem with the "Access-Control-Allow-Origin" error
var url = 'https://app1pub.smappee.net/dev/v1/oauth2/token';
// ajax call
$.ajax({
type: "POST",
url: url,
data: {"grant_type": "password", "client_id": client_id, "client_secret": client_secret,"username": username,"password": password},
beforeSend : function(xhr) {
xhr.setRequestHeader("POST", "/dev/v1/oauth2/token HTTP/1.1");
xhr.setRequestHeader("HOST", "app1pub.smappee.net");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
},
error : function() {
// error handler
},
success: function(data) {
// success handler
alert(data["access_token"])
}
I have test code for WordPress here.
jQuery(document).ready(function($) {
var link = 'http://000.00.00.00/cgi-bin/test.cgi';
$("#sub").click(function() {
$.ajax({
type:'POST',
url: link,
crossDomain: true,
crossOrigin: true,
headers: {
'Accept': 'application/json',
'Content-Type': 'text/html'
},
dataType: "json",
success: function(data) {
console.log(JSON.stringify(data));
},
error: function(e) {
console.log("Error: " + e);
},
});
});
the request seems fine because when i view my chrome network > headers tab status code is OK but the problem is that there is no data. I should have a working output like this..
{ "loyalty" : { "status" : { "rows" : "1", "sql" : "success", "result" : "ok" }, "data" : [ { "card_number" : "1410104000350018" , "card_type" : "BEAUTY ADDICT" , "first_name" : "TINA" , "middle_initial" : "M" , "last_name" : "LIM" } ] } }
You can use JSONP to get data from other domain than your javascript host, which is something like blow:
$("#sub").click(function() {
$.ajax({
url: link,
dataType:'jsonp',
jsonp:'callback',
success: function(data) {
console.log(JSON.stringify(data));
},
error: function(e) {
console.log("Error: " + e);
},
});
and because JSONP transmit data through GET, so In your server side code you need retrieve data from $_GET like this(if you use PHP):
$your_param = $_GET['your_param'];
$callBack = $_GET['callback'];
//do something .....and get $result
echo($callBack . '(' .json_encode($result) . ')');
Hi there are already lots of threads related to this problem.
But still i got stuck into the same . When I am trying to access this REST api, I couldnt able to get the response. I cannot control server side response header because its public API .can any body help on this.
Below is my code
$(document).ready(function() {
$("#medication").autocomplete({
select : function(request, response) {
//$(this).value(response.item.value);
getMedicationIdByName(response.item.value);
},
search : function(){$(this).addClass('working');},
open : function(){$(this).removeClass('working');},
source : function(request, response) {
$.ajax({
headers : {
Accept : "application/json; charset=utf-8",
"Content-Type" : "application/json; charset=utf-8"
},
type : "GET",
url : "http://rxnav.nlm.nih.gov/REST/spellingsuggestions",
data : "name="+ request.term,
crossDomain: 'true',
dataFil ter : function(data) {
return data;
},
success : function(data) {
try {
//alert("success!!"+JSON.stringify(data));
data = data.suggestionGroup.suggestionList["suggestion"]+ "";
data = data.split(",");
response($.map(data,function(item) {
//alert("success!!"+JSON.stringify(item))
return {
value : item
};
}));
} catch (e) {
alert(e);
}
},
error : function() {
alert('Cannot connect to REST API!!!');
}
});
},
minLength : 4
});
});
You need to set dataType to jsonp in your ajax request.
type: "GET",
headers: {
Accept : "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
url: "http://rxnav.nlm.nih.gov/REST/spellingsuggestions",
data: { name: "bard"},
dataType: "jsonp",
crossdomain: true,