Redirect as response to Ajax request ends up returning empty - ajax

We are using Primefaces 3M4 and one of our pages has a p:dataTable which uses ajax calls for events:
<p:ajax event="rowSelect" update=":newsForm:newsDlg" oncomplete="newsDlg.show();"/>
When the session times out the page gets redirected to /login.xhtml which works fine for non-ajax actions (menu items, etc) but when I select a row in the datatable after the session has expired the page doesn't change to the login page and in Firebug I see the following:
Under dashboard.xhtml Headers section of Firebug
Response Headers
Server Apache-Coyote/1.1
X-Powered-By JSF/2.0
Location http://localhost:8080/RetailerPortal/faces/login.xhtml
Content-Length 0
Date Fri, 11 Nov 2011 18:32:42 GMT
Request Headers
Host localhost:8080
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0
Accept application/xml, text/xml, */*; q=0.01
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection keep-alive
Content-Type application/x-www-form-urlencoded; charset=UTF-8
Faces-Request partial/ajax
X-Requested-With XMLHttpRequest
Referer http://localhost:8080/RetailerPortal/faces/dashboard.xhtml
Content-Length 389
Cookie csfcfc=_30Xsr; JSESSIONID=fg1bV1sZkzKIgNtkH0bz0N0f; JSESSIONID=C65BF4EED70299ABFE4B73614118295E
Under dashboard.xhtml Response
<?xml version='1.0' encoding='ISO-8859-1'?>
<partial-response><changes><update id="javax.faces.ViewState"><![CDATA[-3728406524126180805:2441995557020829808]]></update></changes></partial-response>
Under dashbaoard.xhtml Post
Parametersapplication/x-www-form-urlencoded
javax.faces.ViewState 7521050094575005695:7928145831130537413
javax.faces.behavior.even... rowSelect
javax.faces.partial.ajax true
javax.faces.partial.event rowSelect
javax.faces.partial.execu... newsForm:newsTable
javax.faces.partial.rende... newsForm:newsDlg
javax.faces.source newsForm:newsTable
newsForm newsForm
newsForm:newsTable_instan... 3
newsForm:newsTable_select... 3
Source
newsForm=newsForm&newsForm%3AnewsTable_selection=3&javax.faces.ViewState=7521050094575005695%3A7928145831130537413&javax.faces.partial.ajax=true&javax.faces.source=newsForm:newsTable&javax.faces.partial.execute=newsForm:newsTable&javax.faces.partial.render=newsForm:newsDlg&javax.faces.behavior.event=rowSelect&javax.faces.partial.event=rowSelect&newsForm:newsTable_instantSelectedRowKey=3
Under login.xhtml's headers
Response Headers
Server Apache-Coyote/1.1
X-Powered-By JSF/2.0
Cache-Control no-cache
Set-Cookie JSESSIONID=MdhyizD+8IkuFvLZD+6jWlUz; Path=/RetailerPortal
Content-Type text/xml;charset=UTF-8
Content-Length 196
Date Fri, 11 Nov 2011 18:32:42 GMT
Request Headers
Host localhost:8080
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0
Accept application/xml, text/xml, */*; q=0.01
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection keep-alive
Referer http://localhost:8080/RetailerPortal/faces/dashboard.xhtml
X-Requested-With XMLHttpRequest
Faces-Request partial/ajax
Content-Type application/x-www-form-urlencoded
Cookie csfcfc=_30Xsr; JSESSIONID=fg1bV1sZkzKIgNtkH0bz0N0f; JSESSIONID=C65BF4EED70299ABFE4B73614118295E
Under login.xhtml's XML section
XML Parsing Error: no element found Location: moz-nullprincipal:{6ccf85cf-5c69-438c-a9bb-e66423a36a48} Line Number 1, Column 1:
^
Response code
HttpServletResponse servResponse = (HttpServletResponse) response;
servResponse.sendRedirect("login.xhtml");
servResponse.setHeader("Access-Control-Allow-Origin", "*");

Just a guess--
If you're trying to redirect from an ajax response, you can't do that 301/302 style-- you have to send a message back to the browser and have the browser redirect via javascript.
Probably the non-ajax ones are working because they're using 301/302s.

I found the answer to this question in this blog
with the relevant code for at the bottom of the blog post in the doRedirect method.

Related

Getting 401 Response Code in Jmeter when I tried to see the View Result

Am getting 401 Response code while running my Jmeter script. Here is the sample result, request headers, response body, response headers.
Sample Result:
Thread Name:Thread Group 1-1
Sample Start:2022-05-04 20:13:44 IST
Load time:226
Connect Time:0
Latency:226
Size in bytes:591
Sent bytes:876
Headers size in bytes:417
Body size in bytes:174
Sample Count:1
Error Count:1
Data type ("text"|"bin"|""):text
Response code:401
Response message:
Request Headers:
Connection: keep-alive
Authorization: Bearer 0rPuk9bYwyE=ZXlKaGJHY2lPaUpJVXpVeE1pSjkuZXlKemRXSWlPaUpPWVhabFpXNTJaV3h3ZFhKcFFHZHZZWFZrYVhSekxtTnZiU0lzSW1saGRDSTZNVFkxTVRZMk9EZzBNQ3dpWlhod0lqb3hOalV4TnpZNE9EUXdMQ0pxZEdraU9pSmxOREF4WlRZNU1pMWxPVFJtTFRRd01XWXRPR0psTlMwMU1tRXdaR1ptTkdSaFpUVWlMQ0pwYzNNaU9pSXpOamN3TURjMVppMWpZemhpTFRRd1lURXRZakEwT1MxbE4yVXhZMlkxWW1GaFpXVWlmUS5KQjdBOUdyS1I0bWE3N1VieXcySm5xZ3RuQjJJdHR6WVVJWTBZcU13Z1Ztb3AxeXpsNkpzRHF2NDlpVHAwTHhDN1JqNXRPT1dWSnFUeWs5bW5BZTkxUQ==
Referer: http://18.133.204.151/
Accept-Language: en-US,en;q=0.5
Origin: http://18.133.204.151
Content-Type: application/json
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0
Accept: application/json
Content-Length: 2
Host: 18.133.204.151:8080
Response Body:
{"timestamp":"2022-05-04T14:43:44.476+0000","status":401,"error":"Unauthorized","message":"Error -> Unauthorized","path":"/webapp/api/audits/schedule/status/list"}
Response Headers:
HTTP/1.1 401
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: *
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Wed, 04 May 2022 14:43:44 GMT
Can someone please help me in resolving the issue. I tried in many ways and nothing helping me in resolving this.
Thanks in advance.
As per 401 Unauthorized status code description:
401 Unauthorized
The HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code indicates that the client request has not been completed because it lacks valid authentication credentials for the requested resource.
If this Bearer token is recorded you won't be able to replay the request successfully because the token needs to be correlated. Check out Using Regular Expressions to Extract Tokens and Session IDs to Variables article for example solution (you might need to amend it to your application specifics)

Browser auth popup not showing up in case of ajax cors with basic authentication request

From a web page of domain A, I am firing up an ajax request to domain B in order to get JSON for which basic auth is configured on domain B. I have access to the code on both the domains. I configured the all the required CORS header on domain B (Even made Access-Control-Allow-Origin header value specific and not "*", after reading some stackoverflow) What I am expecting is browser basic auth pop up, But POST request just fails with 401.I can see that server has responded with expected response header for PRE-FLIGHT OPTION request, below the request & response headers of the OPTION & actual POST method call that happens
***OPTION REQUEST***
Host: DOMAIN_B:8085
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: x-requested-with
Referer: http://DOMAIN_A:2280/app/
Origin: http://DOMAIN_A:2280
Connection: keep-alive
***OPTION RESPONSE***
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: http://DOMAIN_A:2280
Vary: Origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: Content-Type,Authorization,x-requested-with
Access-Control-Max-Age: 1
Allow: GET,POST
Content-Type: text/html; charset=utf-8
Content-Length: 8
Date: Fri, 04 Jan 2019 12:48:48 GMT
Connection: keep-alive
*** ACTUAL POST REQUEST***
Host: DOMAIN_B:8085
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://DOMAIN_A:2280/app/
X-Requested-With: XMLHttpRequest
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 105
Origin: http://DOMAIN_A:2280
Connection: keep-alive
*** ACTUAL POST REQUEST***
HTTP/1.1 401 Unauthorized
X-Powered-By: Express
Vary: X-HTTP-Method-Override, Origin
Access-Control-Allow-Origin: http://DOMAIN_A:2280
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST,GET,PUT,DELETE
Access-Control-Allow-Headers: Content-Type,Authorization,x-requested-with
Access-Control-Max-Age: 1
WWW-Authenticate: Basic realm=artist
Content-Type: text/plain; charset=utf-8
Content-Length: 12
Date: Fri, 04 Jan 2019 12:48:48 GMT
Connection: keep-alive
So its expected that browser looking at the response of the POST call(401 HTTP code & WWW-Authenticate header) should get prompted to show the native authentication pop up, But it's not doing so. I am not sure what I am doing wrong here. Showing custom form to capture the credential and passing them in "Authorization" header using btoa function is not an option
Appreciate any help, I am ripping my hair apart here!!!
use basic-auth npm plugin
const auth = require('basic-auth');
app.use(function (request, response, next) {
var user = auth(request);
console.log("user => ",user);
if (!user || !user.name || !user.pass) {
response.set('WWW-Authenticate', 'Basic realm="example"');
return response.status(401).send();
}
return next();
});

Issues calling saveChanges with Breezjs

I'm trying to get breeze to work with my webapi/odata service against an Entity framework model with a sql backend.
I've got it to retrieve data from my database, bit am having trouble when I do a createEntity() and then call saveChanges().
I've configured my batch route like this
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// Web API routes
config.Routes.MapHttpBatchRoute(
routeName: "WebApiBatch",
routeTemplate: "odata/$batch",
batchHandler: new System.Web.Http.Batch.DefaultHttpBatchHandler(GlobalConfiguration.DefaultServer));
When I call save changes I get an http 500 server error, with the message:
Invalid 'HttpContent' instance provided. It does not have a content type header with a value of 'application/http; msgtype=request'.
Parameter name: content
the stream sent to the server is :
POST http://gx9020-01:91/odata/$batch HTTP/1.1
Accept: multipart/mixed
DataServiceVersion: 2.0
Content-Type: multipart/mixed;boundary=batch_9245-db9a-4873
MaxDataServiceVersion: 3.0
Referer: http://localhost:61678/WebForm1.aspx
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Connection: Keep-Alive
Content-Length: 731
DNT: 1
Host: gx9020-01:91
Pragma: no-cache
--batch_9245-db9a-4873
Content-Type: multipart/mixed; boundary=changeset_0952-3d90-c3e2
--changeset_0952-3d90-c3e2
Content-Type: application/http
Content-Transfer-Encoding: binary
POST odata/MAP_Counterparty HTTP/1.1
Content-ID: 1
DataServiceVersion: 2.0
Accept: application/atomsvc+xml;q=0.8, application/json;odata=fullmetadata;q=0.7, application/json;q=0.5, */*;q=0.1
Content-Type: application/json
MaxDataServiceVersion: 3.0
{"MAP_CounterpartyID":-1,"SOURCE_SYSTEM":null,"TARGET_SYSTEM":null,"SOURCE_CODE":null,"TARGET_CODE":null,"TARGET_CODE2":null,"DRT_ID":null,"CREATE_DATETIME":null,"MODIFY_DATETIME":null,"Create_User":null,"Modify_User":null}
--changeset_0952-3d90-c3e2--
--batch_9245-db9a-4873--
How can I get the saveChanges() working?
I found the problem. I was using DefaultHttpBatchHandler instead of DefaultODataBatchHandler.

Chrome extension unable to get data from a server after switch to https due to Origin Control

I've been battling with Chromium, jQuery and AJAX. My extension takes some resources from some sites using ajax, then parse the results and store it somewhere. One of those sites decided to do the jump to https. Neat. I just have to change the http for https, and fix any problem I hit down the road. No joy.
I use the following ajax method to get the stuff (is the smallest unit I could reproduce):
$.ajax({
url: "https://reader.japanzai.com/search/",
type: 'POST',
data: {
'search': "onna"
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
headers: {
'Access-Control-Allow-Origin': '*'
}})
Lets ignore for a while that I've set the headers twice, since just using one don't work either and throw the result:
OPTIONS https://reader.japanzai.com/search/ No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome-extension://nhjloagockgobfpopemejpgjjechcpfd' is therefore not allowed access. jquery.js:5
x.support.cors.e.crossDomain.send jquery.js:5
x.extend.ajax jquery.js:5
(anonymous function) VM4000:2
InjectedScript._evaluateOn VM3770:581
InjectedScript._evaluateAndWrap VM3770:540
InjectedScript.evaluate VM3770:459
XMLHttpRequest cannot load https://reader.japanzai.com/search/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome-extension://nhjloagockgobfpopemejpgjjechcpfd' is therefore not allowed access. lab.html:1
As you can see, it says that the request header is not present, which is true following the http request:
Request URL:https://reader.japanzai.com/search/
Request Method:OPTIONS
Status Code:200 OK
Request Headersview parsed
OPTIONS https://reader.japanzai.com/search/ HTTP/1.1
origin: chrome-extension://nhjloagockgobfpopemejpgjjechcpfd
access-control-request-method: POST
dnt: 1
accept-encoding: gzip,deflate,sdch
host: reader.japanzai.com
accept-language: es,en-US;q=0.8,en;q=0.6
method: OPTIONS
user-agent: Mozilla/5.0 (X11; Linux i686 (x86_64)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
accept: */*
url: /search/
scheme: https
version: HTTP/1.1
access-control-request-headers: access-control-allow-origin, accept, content-type
Response:
HTTP/1.1 200 OK
cache-control: post-check=0, pre-check=0, max-age=0
content-encoding: gzip
content-type: text/html
date: Thu, 13 Feb 2014 22:58:03 GMT
expires: Sat, 01 Jan 2000 00:00:01 GMT
last-modified: Thu, 13 Feb 2014 22:58:03 GMT
pragma: no-cache
server: nginx/1.5.8
set-cookie: ci_session=U3Q14aq8Q7W4KVifDyLi7%2B3lppr%2FS4BNmW1kD9t60H7dz73M5KMs1jgBo8ZrilKoswn63PvCl1sOldPs1RCl6NdiP1VZeekoMTISyQenQZU0F8yUC0odw6WuMUE5I%2FY%2Bfvddv2YH06b2pxyyNBDZnNn%2BLnLzPrRYBXHuAjFbTyucX%2FMLUUM2cwKLzaK3ILKPhxy8FXW%2FI%2F9EPPbwo%2B8nmbPwOeqDfpDdu61F5yzUU8KjfUo7MwwFIXyGWtqbjbF3PCKNZrY%2F3Cj77DgCpcCbTTKZ%2BVzrdw16oGVDg1dP8lQgSof89rLNqUlQSj60tCVzZ27oPNh9OvvTNJ92tYkTHDukG4dyv21yM4M3PACZ%2FKVNP0i2UWHbBujADPSsrGJhJxPzBsuRDLcPtDcBtuaXA4LLMoGoYW6SxYk%2BseltMvk%3D; expires=Fri, 14-Feb-2014 00:58:03 GMT; path=/
set-cookie: ci_session=tQT8qmNRnMRN2Oj3moCdZg9VNEEsPxi3t88g2SpYQxahFr%2FpiEpQFzsO2mLTp1bPlsGLmqQGnMUiuwFpLYNIneNHtU%2BoKkVOcnR8ZKxPd0FDrkW%2BqT0N2IIsV%2BC%2FXQX%2BZUkLg1E4iP6u%2F0%2Fjk1t%2BAwcwhoC0M3zODuEKv1l9JMFo%2B1g4%2BhIOp%2FHTzBnlMvE2KjanXJR55F3DOHdyi4MvQb1vzgWEZTTAfhZ3bkQPkKe41ZCJYQTw%2FrDfry8n2h43UKPc1IF4tWp%2BKh0yhux%2FsBn84meT3xR%2Bpba9ffeZObrQyVomKlmJg9oRkKvlhR4MlNsiIeIZEvtP52ns0X1uF%2B7Pg6RpcMihe1u2S0%2Fbz5wm75vQ6tyykmFp5qfnoDgXB6J7RmbBQy4GTOFEA2zqN3V6QXT71cSn%2B1ARd9GtNMA%3D; expires=Fri, 14-Feb-2014 00:58:03 GMT; path=/
status: 200 OK
strict-transport-security: max-age=31536000
vary: Accept-Encoding
version: HTTP/1.1
x-powered-by: PHP/5.4.4-14+deb7u7
So, I'm missing something obvious here or there's just no way to do this?
I followed abraham advice and added the site to the permissions field in the manifest. It worked, the only bad thing is that if another site decides to move to https I need to release a new version, so this is what I ended doing:
"permissions" : [
"tabs",
"*://*/*",
"https://ssl10.ovh.net/*",
"unlimited_storage",
"clipboardWrite",
The important part here is "*://*/*" which includes anything from http and https.

Guice servlet 405 err: seems to not set Content-type set to "text/json" for MediaType.APPLICATION_JSON

I'm making a call from jQGrid to a Guice servlet that has the following binding:
#Produces({MediaType.APPLICATION_JSON})
#Path("/{param}")
public String getJson(#PathParam("param") String param) {
...
return return json.toString();
}
Requesting the url directly, I can see the JSON. When jqgrid executes the request, I get 405 method not allowed response. I've seen this happen before when the returning page doesn't have the Content-type set to "text/json" (jqgrid is not very flexible here).
HERE IS THE REQUEST:
Key Value
Request POST /myapp/json/jqgrid/json ... HTTP/1.1
x-requested-with XMLHttpRequest
Accept-Language en-us
Referer http://localhost:8080/myapp/myPage...
Accept application/json, text/javascript, /
Content-Type application/x-www-form-urlencoded
Accept-Encoding gzip, deflate
User-Agent Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Host localhost:8080
Content-Length 63
Connection Keep-Alive
Cache-Control no-cache
HERE IS THE RESPONSE:
Key Value
Response HTTP/1.1 405 Method Not Allowed
Server Apache-Coyote/1.1
Allow GET,OPTIONS,HEAD
Content-Type text/html;charset=utf-8
Content-Length 1034
Any thoughts on how to get the guice servlet to set the Content-type to "text/json" and allow the response?
This one is solved. I was using a #GET annotation and jQGrid was issuing a post. I changed the #POST and it started working. This may solve the problem for others with related 405 errors.

Resources