I have an MVC project secured with a asp.net identity:
This is my Login function:
self.login = function () {
event.preventDefault();
if (!$('#formLogin').valid()) {
return false;
}
var loginData = {
grant_type: 'password',
username: self.userName(),
password: self.password()
};
$.ajax({
type: 'POST',
url: '/API/Token',
data: loginData
}).done(function (data) {
// Cache the access token in session storage.
sessionStorage.setItem(tokenKey, data.access_token);
self.authenticate();
//change status of Login button to Logout
self.redirect('Users');
}).fail(showError);
}
self.authenticate = function () {
self.token = sessionStorage.getItem(tokenKey);
var headers = {};
console.log(self.token);
if (self.token) {
headers.Authorization = 'Bearer ' + self.token;
}
$.ajaxSetup({
headers: headers
});
}
That works fine, I get the token successfully and the headers are set up correctly.
The problem is that when I try to send a request- for example:
self.getUsers = function () {
$.get("/API/Users/GetUsers/");
}
I get a 401 error from the server:
"message": "Authorization has been denied for this request."
What am I doing wrong?
According to the official documentation of the jQuery.ajax, use this to set custom headers of each request:
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', '...');
}
});
Related
I'm trying to login in Joomla! by Ajax with default login module. But it always return success-
$('a.login_submit').click(function(e){
e.preventDefault();
$username = $('#username').val();
$password = $('#password').val();
$.ajax({
type: 'post',
url: 'index.php?option=com_ajax&module=login&method=user.login&format=json',
data: {username: $username, password: $password},
success: function(){
$('.error').hide();
$('.success').show();
},
error: function(){
$('.success').hide();
$('.error').show();
}
});
});
Why this always return true?
It'll be always a success (provided you have a connection with a server). You must analyse the response on success to validate the credentials.
success: function(data){
if ( data === "Correct" ) {
//handle login
}
else {
alert(data);
}
}
I have tried
class UsersController extends AppController
{
public function beforeFilter(Event $event)
{
$this->getEventManager()->off($this->Csrf);
}
public function ajaxEdit($id = null)
{
$this->autoRender = false;
debug($id);
debug($this->request->getData());
}
And I am using ajax code
$(document).ready(function(){
$('#user-profile').change(function(){
$('.loader-body').show();
var form = $('#user-profile-image')[0];
var formData = new FormData(form);
var tutorial_id = $('#user-file-id').val();
$.ajax({
url :"/users/ajax-edit/"+tutorial_id,
method:"POST",
data:formData,
contentType:false,
cache: false,
processData:false,
success:function(data){
let parseData = $.parseJSON(data);
if (parseData.status === true) {
location.reload();
var value = parseData.url;
console.log(value);
} else {
alert(parseData.message);
}
}
});
});
});
I have followed help from these links
CakePHP ajax CSRF token mismatch
2 https://book.cakephp.org/3.0/en/controllers/components/csrf.html
Getting CSRF token mismatch (see attached image)
https://i.stack.imgur.com/FsVZu.png
First of all if your are using POST method in your ajax call then you should send tutorial_id as data instead of sending it in the url.
You can resolve this by sending you CSRF token through a special X-CSRF-Token header in your ajax call.
https://book.cakephp.org/3.0/en/controllers/components/csrf.html
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('[name="_csrfToken"]').val());
},
OR
You can disable CSRF component[Not recommended by the Cakephp] for your ajax action like:
public function beforeFilter(Event $event) {
if (in_array($this->request->action, ['ajaxEdit'])) {
$this->eventManager()->off($this->Csrf);
}
}
We are new to angular js.
We tried http request using $http.get it is working fine. But in post request it is creating an issue, it comes to success and show bad parameter error code 103.
Same we have tried in ajax request using $.ajax({}), and it is working fine.
I have also paste my code.
Can anyone help us out?
mainApp.controller('registrationCtrl', function($scope, $location, $http) {
$scope.registration = function() {
console.log("registration called");
var ws_url = "http://apparelinindia.com/selfiestandoff/WebServices/register";
var request = $http({
method: "post",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
dataType: 'json',
headers: {
'Content-Type': 'application/json'
}
});
request.success(function(data) {
console.log("Success" + data);
});
request.error(function(error) {
console.log("Success" + JSON.stringify(error));
});
};
});
You can use http Post in following way:
var request = $http.post(ws_url, {
user_email: $scope.email,
user_password: $scope.password
});
The name of the http method should be written in uppercase. Also, the property datatype is not awaited by $http, you should remove it:
var request = $http({
method: "POST",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
headers: {
'Content-Type': 'application/json'
}
});
Note, in the above call to $http you are setting the header 'Content-Type': 'application/json'. But this header is automatically injected by $http (see $http documentation), therefore you can remove it, and use the short syntax:
var request = $http.post(ws_url, data);
with data equals to:
{
user_email: $scope.email,
user_password: $scope.password
}
Are You Getting this error ??
{"status":false,"error":{"code":"103","message":"Required Parameters not found"}}
If Yes, Its Not your Problem Contact the Web service provider.
Ask him to give the valid parameter
Things tried:
commented lines regarding webdav
edited iis config file i.e added PUT,DELETE verbs
jQuery .support.cors = true;
Error: 405: method not allowed (in chrome debugger)
response is going to ajax error.
ajax call code:
jQuery.support.cors = true;
function CheckLogin() {
var user = { "UserName": $('#UserName').val(), "Password": $('#Passsword').val() };
user = JSON.stringify(user);
$.ajax({
url: 'http://localhost/MvcRazorClient/api/HomeApi/SignIn',
//here i changed the webapi route to api/controller/action
type: "PUT",
data: user,
async: false,
crossDomain: true,
contentType: "application/json",
dataType: 'json',
success: function (data) {
if (data == true) {
alert('true')
} else {
alert('false');
}
},
error: function () {
alert('er');
}
});
}
my api controller code:
[HttpPut]
public bool SignIn(User u)
//here i tried parameters as "dynamic u" and "HttpRequestMessage u". nothing worked
{
return true;
}
help please.
i didnt disable webDAV in iis .
path: Control Panel\All Control Panel Items\Programs and Features->iis->world wide web services->Common Http Features->(uncheck) webDAV
I'm making an ajax request to retrieve json data from webtrends - a service that requires a login. I'm passing the username and password in my ajax request, but still gives me a 401 unauthorized error. I've tried 3 different methods - but no luck. Can someone pls help me find a solution?
1. $.getJSON('https://ws.webtrends.com/..?jsoncallback=?', { format: 'jsonp', suppress_error_codes: 'true', username: 'xxx', password: 'xxx', cache: 'false' }, function(json) {
console.log(json);
alert(json);
});
2. $.ajax({
url: "https://ws.webtrends.com/../?callback=?",
type: 'GET',
cache: false,
dataType: 'jsonp',
processData: false,
data: 'get=login',
username: "xxx",
password: "xxx",
beforeSend: function (req) {
req.setRequestHeader('Authorization', "xxx:xxx");
},
success: function (response) {
alert("success");
},
error: function(error) {
alert("error");
}
});
3. window.onload=function() {
var url = "https://ws.webtrends.com/...?username=xxx&password=xxx&callback=?";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
function parseRequest(response) {
try {
alert(response);
}
catch(an_exception) {
alert('error');
}
}
Method 3 might work when you use a named callback function and use basic authentication in the url. Mind though that a lot of browsers don't accept url-authentication (or whatever the name is). If you want to try it, you can rewrite it like this:
window.onload = function() {
var url = "https://xxx:xxx#ws.webtrends.com/...?callback=parseRequest";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
function parseRequest(response) {
try {
alert(response);
}
catch(an_exception) {
alert('error');
}
}