Spark-java redirect - browser does not redirect - http

Ok, so I try to follow Spark documentation and I want to perform simple redirect in my Single Page Application. My code looks like this:
post("/users/login", (req, res) -> {
ObjectMapper mapper = new ObjectMapper();
User creation = mapper.readValue(req.body(), User.class);
User user = userService.getUser(creation.getLogin());
if (user.getPassword().equals(creation.getPassword())) {
req.session().attribute("userid", creation.getLogin());
System.out.println("OK");
res.status(201);
res.redirect("/index.html");
return "";
}
System.out.println("BAD");
return null;
} , json());
Basically, I have three static html files: registration.html, login.html and index.html. I read stuff concerning staticFileLocation so I added at the beginning of main function following line of code:
staticFileLocation("/public");
When I type correct login and password I find in the network view in Chrome that I have GET request with status 200, OK, to http://localhost:4567/index.html. However, the browser does nothing and does not redirect me to that page. Can you tell me what I am doing wrong?
EDIT:
Here's javascript code that handles log in on the client side:
app.controller('LoginUserCtrl', function($scope, $http) {
$scope.loginUser = {};
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'http://localhost:4567/users/login',
data : $scope.loginUser,
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function() {
console.log("User logged successfully");
console.log($scope.loginUser);
}).error(function() {
console.log("Unknown error while logging user");
});
};
});

What's wrong is that you're redirecting to an HTML page in a post endpoint that's supposed to return Json data. You have to return a single json if authentication succeeded or failed, like {"auth": "OK"} or {"auth": "NOK"}, and decide where to redirect to from Javascript based in it's information.

It's because res.redirect will send a redirect http header(HTTP status values 301, 302, 303 and 307) to the browser,
but the browser only can redirect in get, NOT work in post or put or delete (Tested in chrome. Notice that a redirect request was sent by browser, but the page just not change...).
See:
http://www.alanflavell.org.uk/www/post-redirect.html

Related

How to show body of a bad request response in angular 4?

To provide login error message I added a message in the constructor of Bad Request Response which shows in the postman while testing an web api.
Like this: return BadRequest("Error Message");
Now I want to get that message and display in a component in the client side. But I don't know how to retrieve that. I am trying like this:
signIn() {
this.authService.login(this.loginCredentials).subscribe(result=>{
if(result){
let returnUrl=this.route.snapshot.queryParamMap.get('returnUrl');
this.router.navigate([returnUrl||'/']);
}
},
(err) => {
this.loginMessage=true;
console.log(err.body);
this.invalidLogin=true;
});
}
Finally got it. It will be
console.log(err.body);

Scraping an ASP.NET website with NodeJS

i am trying to login to my supplier website programatically and get the resseller price by code. i have my username and password provided by the supplier to use in the website which is powred by ASP.NET. i tried to use the request module but got no luck with it.
this the code i used so far :
var request = require('request');
var j = request.jar();
var request = request.defaults({ jar : j }) //it will make the session default for every request
//...
request({
url:"https://www.XXXXX.com/login.aspx",
method:"POST",
form:{
ctl00$cpholder$txtUserName:"YYYYYYYY",
ctl00$cpholder$txtPassword:"ZZZZZZZZ"
}
},
function(err,response,body){
console.log(err);
// here i try to access the product page like a reseller
request({
url:"https://www.XXXXXX.com/productdetails.aspx?id=20000028&itemno=90NB0CL1-M08420",
method:"GET",
}, function(err, response, body){
console.log(err);
//Some logic
});
});
}
this is the login form code ( in pastebin because it is very long )
https://pastebin.com/kwuRdLX4
please help

app.post on parse heroku server is unauthorized

I am trying to post to my server from twilio, but I am getting a 403 error. Basically my parse-heroku serve is rejecting any request from twilio. I am working with TWIMLAPP and masked numbers. I am having trouble posting to a function in my index file when a text goes through. In my TWIMLAPP my message url is https://parseserver.herokuapp.com/parse/index/sms Any help is appreciated. These are the errors in twilio
var app = express();
app.use(require('body-parser').urlencoded());
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'https://www.twilio.com');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader("X-Parse-Master-Key", "xxxxxxx");
res.setHeader("X-Parse-Application-Id", "xxxxxx");
// Pass to next layer of middleware
next();
});
app.post('/sms', twilio.webhook({ validate: false }), function (req, res) {
console.log("use-sms")
from = req.body.From;
to = req.body.To;
body = req.body.Body;
gatherOutgoingNumber(from, to)
.then(function (outgoingPhoneNumber) {
var twiml = new twilio.TwimlResponse();
twiml.message(body, { to: outgoingPhoneNumber });
res.type('text/xml');
res.send(twiml.toString());
});
});

XDomainRequest in IE is giving Access is Denied error

This is the code I am using is as follows down below:
I am using IE9 and am unable to see the request being sent in the Network tab. I do have Access-Control headers set in the JSP as:
<% response.setHeader("Access-Control-Allow-Origin", "*");%>
Code to get the AJAX HTML Content from the JSP:
if ($.browser.msie && window.XDomainRequest) {
var xdr = new window.XDomainRequest();
xdr.open("GET", "http://dev01.org:11110/crs/qw/qw.jsp?&_=" + Math.random());
xdr.contentType = "text/plain";
xdr.timeout = 5000;
xdr.onerror = function () {
console.log('we have an error!');
}
xdr.onprogress = function () {
console.log('this sucks!');
};
xdr.ontimeout = function () {
console.log('it timed out!');
};
xdr.onopen = function () {
console.log('we open the xdomainrequest');
};
xdr.onload = function() {
alert(xdr.responseText);
};
xdr.send(null);
} else { ...... }
I am getting a Access is Denied Error. Any help would be much appreciated!
Requests must be targeted to the same scheme as the hosting page
In your example you are doing request to:
http://dev01 ...
And you should do this from HTTP protocol.
For example:
If your site, where js script is located: http://dev.org
You can do this:
xhr = new XDomainRequest();
xhr.open("GET", "http://dev01.org?p=1");
but this throws "Access denied":
xhr = new XDomainRequest();
xhr.open("GET", "https://dev01.org?p=1");
My experience with XDomainRequest is that it doesn't respect Access-Control-Allow-Origin: *. Instead, you must specify the domain. This can be obtained from the HTTP_REFERER header if you need to dynamically generate it, or if you are only expecting requests from one domain you can set it manually. This article might help.
<% response.setHeader("Access-Control-Allow-Origin", "http://dev01.org");%>

HandleUnauthorizedRequest in ASP.Net Web API

I am developing a ASP.Net Web API application and I have used AuthorizeAttribute for the authentication. When the authentication fails, the code that executes is this.
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
return;
}
This code results to display a Unauthorized request page from the browser but what I want is to display a custom page which I have designed. How do I do that?
Check this out: http://weblogs.asp.net/jgalloway/archive/2012/03/23/asp-net-web-api-screencast-series-part-6-authorization.aspx
What it basically says, you have to check the result code on the client side, and in case it is 401 (Unauthorized), redirect the user to the custom page you've designed:
$(function () {
$("#getCommentsFormsAuth").click(function () {
viewModel.comments([]);
$.ajax({ url: "/api/comments",
accepts: "application/json",
cache: false,
statusCode: {
200: function(data) {
viewModel.comments(data);
},
401: function(jqXHR, textStatus, errorThrown) {
self.location = '/Account/Login/';
}
}
});
});
});
I don't think you can redirect to your custom page from within HandleUnathorizedRequest if you are using WebApi. The code result displays Unauthorized request page because that is how your browser responds to 403 code. WebApi works on HttpMessage exchange and by default uses either Json or Xml media type. If you want to return your customized page as text/html then you will have to write your own media formatter as explained here: http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters.

Resources