which cookies/headers should I set? - c#

I should get a protected page from external site, if I call it directly, I get an error:
Bad Request
Postman:
But if I call a login page with valid credentials via Postman:
and then recall THE SAME resource page from the same Postman I got the protected page!:
I have to get the same page on website. I try to implement it by the following way:
var loginXml = "<Request><MsgType>Authenticate</MsgType><SubMsgType>Login</SubMsgType><UserID>my_login</UserID><passwordNotEncrypted>my_password</passwordNotEncrypted></Request>";
$.ajax(
{
url: 'https://address/browserservices.aspx/login',
type: 'POST',
contentType: 'text/xml',
datatype: 'text',
//xhrFields: {
// withCredentials: true
//},
//crossDomain: true,
data: loginXml,
success: function (output, status, xhr) {
alert(xhr.getResponseHeader("Set-Cookie"));
$.ajax({
url: "https://address/RemoteSupport.aspx?id=GUID&pltFrmType=Android&agentversion=13.46",
type: 'GET',
xhrFields: { withCredentials: true },
//crossDomain: true,
success: function (x) { },
error: function (xhr, textStatus) { alert(xhr.status); }
});
},
})
but I get Bad Request again.
Which headers/cookies should I pass to page to open protected page, like it's in Postman?
ADDED 28/01/19
Postman "Cookie" tab after success login request (fail login request has the same):
and "Headers" tab:
as I see, all access-control-allow header are available. What should I pass via ajax?

Based on the information that you have supplied there are two likely scenarios.
Firstly, the cookie that is set by the external site is HttpOnly. This is easy enough to check in Postman, by clicking on the the Cookies tab.
The second option is a little more complex, but the external server has to set the Access Control headers correctly. Again there is a Headers tab to view these. More info on cross domain ajax and headers in this question: Why is jquery's .ajax() method not sending my session cookie?
Finally worth noting, your browser will automatically add a header to indicate that it is an ajax request. You could try adding the X-Requested-With: XMLHttpRequest header in Postman and seeing how it differs from your examples. The external server may well be configured to respond differently to ajax requests than to browser or server-server api requests.
Update
Your Postman update shows that both of those scenarios are true. Unfortunately this means that you cannot achieve your desired result with JavaScript. HttpOnly = true means that the browser will never allow the script on your page to access the cookie.
At this point your best bet is probably to write a little proxy method on your own site that makes the request server to server and then returns the result to your JavaScript code. This should bypass all the above issues albeit you need to make 2 requests instead of 1 for the data.
Take a look at this answer for some code
Struggling trying to get cookie out of response with HttpClient in .net 4.5

Related

How can i integrate PrintFriendly API in asp.NET web form (https://www.printfriendly.com/)? [duplicate]

I'm calling this function from my asp.net form and getting following error on firebug console while calling ajax.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://anotherdomain/test.json. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
var url= 'http://anotherdomain/test.json';
$.ajax({
url: url,
crossOrigin: true,
type: 'GET',
xhrFields: { withCredentials: true },
accept: 'application/json'
}).done(function (data) {
alert(data);
}).fail(function (xhr, textStatus, error) {
var title, message;
switch (xhr.status) {
case 403:
title = xhr.responseJSON.errorSummary;
message = 'Please login to your server before running the test.';
break;
default:
title = 'Invalid URL or Cross-Origin Request Blocked';
message = 'You must explictly add this site (' + window.location.origin + ') to the list of allowed websites in your server.';
break;
}
});
I've done alternate way but still unable to find the solution.
Note: I've no server rights to make server side(API/URL) changes.
This happens generally when you try access another domain's resources.
This is a security feature for avoiding everyone freely accessing any resources of that domain (which can be accessed for example to have an exact same copy of your website on a pirate domain).
The header of the response, even if it's 200OK do not allow other origins (domains, port) to access the resources.
You can fix this problem if you are the owner of both domains:
Solution 1: via .htaccess
To change that, you can write this in the .htaccess of the requested domain file:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
If you only want to give access to one domain, the .htaccess should look like this:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin 'https://my-domain.example'
</IfModule>
Solution 2: set headers the correct way
If you set this into the response header of the requested file, you will allow everyone to access the resources:
Access-Control-Allow-Origin : *
OR
Access-Control-Allow-Origin : http://www.my-domain.example
Server side put this on top of <filename>.php:
header('Access-Control-Allow-Origin: *');
You can set specific domain restriction access:
header('Access-Control-Allow-Origin: https://www.example.com');
in your ajax request, adding:
dataType: "jsonp",
after line :
type: 'GET',
should solve this problem ..
hope this help you
If you are using Express js in backend you can install the package cors, and then use it in your server like this :
const cors = require("cors");
app.use(cors());
This fixed my issue
This worked for me:
Create php file that will download content of another domain page without using js:
<?
//file name: your_php_page.php
echo file_get_contents('http://anotherdomain/test.json');
?>
Then run it in ajax (jquery). Example:
$.ajax({
url: your_php_page.php,
//optional data might be usefull
//type: 'GET',
//dataType: "jsonp",
//dataType: 'xml',
context: document.body
}).done(function(data) {
alert("data");
});
You have to modify your server side code, as given below
public class CorsResponseFilter implements ContainerResponseFilter {
#Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
responseContext.getHeaders().add("Access-Control-Allow-Origin","*");
responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
}
}
You must have got the idea why you are getting this problem after going through above answers.
self.send_header('Access-Control-Allow-Origin', '*')
You just have to add the above line in your server side.
In a pinch, you can use this Chrome Extension to disable CORS on your local browser.
Allow CORS: Access-Control-Allow-Origin Chrome Extension

Login into laravel 5.2 from other domain

I have a project with laravel 5.2. There is another system in .net. What I want is to get login into laravel 5.2 from .net system. For that, I'm making ajax call from .net app to laravel app. But laravel app is throwing TokenMismatchException. I know I have to send csrf token in request. But how to send csrf token from .net app. If anyone knows the answer, it will be appreciated.
Here is my code.
.net app
$.ajax({
type: 'POST',
url: 'http://192.168.1.78/laravel-project/login',
data: {
email: 'xyz#xyz.com',
password: 'pass'
}
}).success(function (response) {
response = $.parseJSON(response);
}).error(function () {
alert('error');
});
You can disable the csrf check on the login uri by editing the VerifyCsrfToken class of your Laravel app:
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'login/*', // Your route url here
];
}
This will make the ajax call to the login route vulnerable to csrf-attacks, but will solve your problem. See it as a workaround / quick fix.
What you really want to do, is to provide the login via an api-call. Since you are using another app to access the laravel app. This is what API's are meant to be used for.
Laravel routes are default handled by the web middleware group, which includes the VerifyCsrfToken class.
What you want to do is specify a new middleware group for you api-calls, which does not include any csrf-checks. I would consider using a package for this, e.g. https://github.com/tymondesigns/jwt-auth
If you need to send more information with javascript try this
jQuery.support.cors = true;
$.ajax({
url: 'http://192.168.1.78/myproject/login',
type: 'POST',
dataType: dataType,
data: data,
crossDomain: true,
cotentType: YOUR_CONTENT_TYPE,
success: successCallback,
error: errorCallback,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', SOMETHING.val());
}
});
To make this script right for your needs, you should read about CORS, crossDomain and xhr.setRequestHeader
You can also use Postman (Chrome extension)
xhr.setRequestHeader
Postman sample
EDIT: Did you read this? Token Mismatch Exception on Login (Laravel)
Regards,

AJAX requests from jquery in android application to WCF Service always fails

I have an application where I fetch a list of requests made by the user based on the idNo provided. The android application uses AJAX to make a request to a .NET WCF Service which in turn returns a IEnumerable of DTO for that request.
Following is the AJAX Code:
$.ajax({
url: baseURL + "RequestStatusList/"+idNo,
cache : false,
type : "GET",
dataType : "json",
contentType : "application/json; charset=utf-8",
crossdomain : true,
success : function(data, tst, xhr) {
//do something here
},
error: function (xhr, tst, err) {
alert(' Please Try Again ' + xhr.status);
}
});
A similar piece of code works in another page in the application, where only the process in success is different, rest all is same.
Here every time the request fails and enters the error section and displays undefined/0 as error. No details about error, hence i cannot get what maybe the problem.
When I debug the server side code I get proper value in the parameter passed and a IEnumerable is formed and returned. What fails is the client side code after successful execution of server code.
Please Help.
Thanks in advance.

Handling errors raised by jQuery Ajax method

I have a page in which I am using a jQuery ajax method to call a simple Webservice which will get some data from the database and bind it to some controls in the page. The ajax method is called on the onchange event of select (here the HTTP request is POST). Following is the jQuery ajax method
function CallAjax(url, jsonData, SucessFunction, FailurFunction) {
$.ajax({
type: "POST",
url: url,
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: SucessFunction,
error: function(){
alert('error occured');
}
});
}
The URL for above method is somepage.aspx/getDataFromDatabse where getDataFromDatabse is the webservice method. Our testers are testing the page using burp suite. When they are directly tying to access the url(www.example.com/somepage.aspx/getDataFromDatabse) in the browser, the HTTP method shown in burp suite is GET and an error is raised and the user is getting redirected to the appropriate page. But when they are directly accessing the above URL and intercepting the request in burp suite and changing GET request to POST request the following error message is displayed directly in the browser:
{"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}
The "error" in the above ajax function is not getting executed and the alert box is not shown and we are able to handle the error. How to handle such an error and redirect the user to a custom page?
It would appear that the response from your server is a valid JSon response, despite the fact that it contains what (to you) reads as an error. As such the $.ajax(...) call is handling the response as a success, not an error.
You can return a valid JSon response and within that response indicate whether there was an error or not, along with any additional info such as a user-friendly error message, a redirect URL, etc.
The error: handler of the $.ajax(...) call should be used for real server response errors (i.e. unhandled 500 errors, timeouts etc.)
For example, your successful JSon response could be something like:
{
success: true,
errorMessage: null,
errorRedirectUrl: null,
data: { .... your successful data response .... }
}
and your failed JSon response (e.g. due to validation problems, not server failures) would look like this:
{
success: false,
errorMessage: 'There was an error processing the request.',
errorRedirectUrl: 'http://....someurl...',
data: null
}
Then you check for response.success == true in the success: option of the $.ajax(....) call, and handle appropriately.
By having a single, consistent structure the success: option handles all ajax requests which complete and then determines whether there was a handled error and what to do with it, such as display an alert to the user, redirect them to a URL, etc...
In contrast, the error: option handles only those ajax requests which didn't come back with a response you can use.
Update:
On your server you are already handling the difference between receiving a GET http request and a POST http request. So, I think your problem is that you also need to detect whether the POST request contains valid data in the format the webservice method needs.
So, your web service needs to decide if the POSTed data in the http request is in a format it expects to receive and if not return an HTTP redirect response (302) rather than returning the error.
You could do this in 2 ways:
Using a Try... Catch... block. Your webservice method already appears to be throwing an exception and returning it, so catch it and then instead of returning it, set up and return a 302 response instead.
If genuine calls to the webservice can generate exceptions under normal operations (this is usually bad!) you'll need to validate the data received in the request to see if it is what the webservice method expects to receive (was data received? was it the right structure as would be sent by the ajax request? etc.)
Note: if the request does contain valid data then there is no easy way to detect whether this came from a genuine source (the ajax call) or a forged request by some other means. There are solutions to this, but they are involved and can require multiple calls for authentication etc.

Dojo 1.8 web service call fails with status: 500 error code

dojo.xhrPost({
url: "Default.aspx/TestMethod",
handleAs: "json",
contentType: "application/json",
postData: dojo.toJson({ }),
load: function (result) {
debugger;
},
error: function (err) {
debugger;
}
});
That is the script I use to make a request to a WebMethod that is exposed in Default.aspx. The method is called TestMethod.
The error that I get is:
Unable to load Default.aspx/TestMethod status: 500
If you need any additional information please let me know.
*Note : I can call the method from the server side and it returns the results as intended.
I've been there. :(
Usually it is a problem with the format of the data that you are passing in. For instance, if your WebMethod has a parameter that is an int and you are passing a string, you will get a failure like this.
I would use a tool like Fiddler http://www.fiddler2.com/fiddler2/ to see what you are sending to the method.
Also turn on what ever server side logging and tracing that you have and use it. One source that is useful for 500 errors (which tend to happen before "your" server code is reached) is Asp.net health monitoring.
There is more info about setting that up and using it at http://msdn.microsoft.com/en-us/library/bb398933(v=vs.100).aspx

Categories

Resources