JSF action listener not called - java

I am using JSF 1.2 and RichFaces 3.3.3, and I have a very strange issue, what the code does is take the name of the media item to be searched and put it in the backing bean attribute searcTitle, and when the user clicks the search button the onSearch action listener populates the results list.
And here's the code
<rich:panelBar>
<rich:panelBarItem>
<rich:tabPanel>
<rich:tab label="Media">
<h:panelGrid columns="1">
<h:panelGrid columns="2">
<h:inputText value="#{media.searchTitle}"/>
<a4j:commandButton value="Search" actionListener="#{media.onSearch}"/>
</h:panelGrid>
<a4j:outputPanel id="mediaSearchResults" ajaxRendered="true">
<rich:dataTable value="#{media.results}" var="item">
<h:column>
<h:outputText value="#{item.title}"/>
</h:column>
</rich:dataTable>
</a4j:outputPanel>
</h:panelGrid>
</rich:tab>
</rich:tabPanel>
</rich:panelBarItem>
</rich:panelBar>
And the backing bean code
private String searchTitle="";
private List<MediaItem> results;
public void setSearchTitle(String title){
getLogger().log(Level.INFO,"At the setter of the search title string");
this.searchTitle = title;
}
public String getSearchTitle(){
return searchTitle;
}
//Setter and getter for the results list;
//Action Listener
public void onSearch(ActionEvent evt){
getLogger().log(Level.INFO,"At the actionListener");
//Some function that searches and populates the results list
populateResults();
}
Now the problem is whenever I click on the search button, the action listener is never called, although while inspecting the page with fire bug a request is sent to the server everytime I click on it, but the action listener itself is not triggered.
Does anyone have a clue why I'm having this issue? I'm a beginner at this, so please keep your words simple.
Thanks in advance.
Here are the Reposne/ Request headers from firebug
Response Headers
Ajax-Response true
Cache-Control no-cache, must-revalidate, max_age=0, no-store
Content-Type text/xml;charset=UTF-8
Date Sat, 02 Jun 2012 16:03:13 GMT
Expires 0
Pragma no-cache
Server Sun GlassFish Enterprise Server v2.1.1
Transfer-Encoding chunked
X-Powered-By Servlet/2.5, JSF/1.2
Request Headers
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en,ar;q=0.7,en-us;q=0.3
Connection keep-alive
Content-Length 17986
Content-Type application/x-www-form-urlencoded; charset=UTF-8
Cookie JSESSIONID=de975352b3adc4f59d57006755ea; JSESSIONID=de682f835c0fa928413ba7e5f59d; form:tree-hi=form:tree:applications:enterpriseApplications
Host localhost:8080
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0
And the link to the xml payload of the response http://justpaste.it/10uh

You should try a f:form or a4j:form around your a4j:commandButton.

Related

Spring CSRF: Ajax giving 403 error even after setting request headers

I have set up CSRF authentication using Spring Security 4.0. While using AJAX i am getting 403 error each time. I have set up the request headers.
The meta tags:
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head>
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
AJAX looks like this:
var token = $("meta[name='_csrf']").attr("th:content");
var header = $("meta[name='_csrf_header']").attr("th:content");
$.ajax({
type : "POST",
url : "/PRIT/Home/PopulateVisits",
async: false,
beforeSend: function(xhr) {
if (header && token) {
xhr.setRequestHeader(header, token);
}
},
.
.
.
I can see the request headers in the ajax request :
> Accept:*/* Accept-Encoding:gzip, deflate, br
> Accept-Language:en-US,en;q=0.9 Cache-Control:no-cache
> Connection:keep-alive Content-Length:9
> Content-Type:application/x-www-form-urlencoded; charset=UTF-8
> Cookie:JSESSIONID=C3CAAD64269BD0B96FF35B87053B5899 Host:localhost:8082
> Origin:http://localhost:8082 Pragma:no-cache
> Referer:http://localhost:8082/PRIT/Login User-Agent:Mozilla/5.0
> (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
> Chrome/63.0.3239.132 Safari/537.36
> X-CSRF-TOKEN:23c07d26-0494-4588-a158-624791258762
> X-Requested-With:XMLHttpRequest
Request URL:http://localhost:8082/PRIT/Home/PopulateVisits
Request Method:POST
Status Code:403
Remote Address:[::1]:8082
Referrer Policy:no-referrer-when-downgrade
I am not sure what's going wrong. The requested controller is never accessed. The controller is like this:
#RequestMapping(value = "/Home/PopulateVisits", method = RequestMethod.POST)
public #ResponseBody List<DataCollectionForm> PopulateVisits(DataCollectionForm dataCollectionForm, HttpServletRequest request) {
I ran into a similar issue, in my case i was invalidating the spring session during login. Make sure you are not invalidating the Spring session anywhere in your controller prior to the request you are trying to access. Spring associates the token with the session, invalidating it would produce a new token.

How can i securely implement CSRF tokens in java

Problem Behind the question :
I was trying to prevent csrf attack in my java web application,In order to implement it i have tried with implementation of X-CSRF-Token,whenever the request was made the request would be transmitted through like this :
POST /sessions HTTP/1.1
Host: sample.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:42.0) Gecko/20100101 Firefox/42.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
X-CSRF-Token: Ma7g2c5tpeJGcenBa0S4rGtPaHLe2o+kO5AXz+Uk2WnpaTp1J9jdZMPcE1mMSLxZ/7BA1nCBxvLKiZwtepKdoA==
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: https://sample.com
Content-Length: 67
now as a attacker what i have tried to achieve this was,i intercepted the post request,instead of attacking token ,i tried to attack the parameter for example see the below request :
POST /sessions HTTP/1.1
Host: sample.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:42.0) Gecko/20100101 Firefox/42.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
testX-CSRF-Token: Ma7g2c5tpeJGcenBa0S4rGtPaHLe2o+kO5AXz+Uk2WnpaTp1J9jdZMPcE1mMSLxZ/7BA1nCBxvLKiZwtepKdoA==
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: https://sample.com
Content-Length: 67
while i tried the above request the CSRF token implementation gets failed ,i was able to successfully bypass csrf injection ,
What would be the best method to mitigate this kind of attack?is it valid csrf injection?how can i optimize my java webapplication for preventing this kind of attacks?
How i implemented java code :
In my xml :
<http>
<!-- ... -->
<csrf disabled="true"/>
</http>
And at my code :
#EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable();
}
}
At form submissions :
<c:url var="logoutUrl" value="/logout"/>
<form action="${logoutUrl}"
method="post">
<input type="submit"
value="Log out" />
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>
</form>
also i followed the recommended methods provided over here
,on the above scenario the csrf fails ,what might be the mitigations?
As per spring's documentation, you can inject your custom RequestMatcher to validate HTTP request for CSRF token. Spring provides you the feature to override the defaults.
See section 16.6 http://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html
class CSRFRequestMatcher implements RequestMatcher{
public boolean matches (HttpServletRequest req){
//Check if request contains valid header name & header value
}
}

Understanding working of enctype = multipart/form-data in spring mvc

In book "Spring in Action" i read , the default content type of a post submission is application/x-www-form-urlencoded and takes the form of name-value pairs separated by ampersands. (I believe these all goes as the body payload of the HTTP POST request.)
I further read, with enctype set to multipart/form-data, each field will be submitted as a distinct part of the POST request and not as just another name-value pair.
Q1> I don't get this line. I am from a REST background and will want to understand what in content of the HTTP POST request has changed ?
The server side code
#RequestMapping(method=RequestMethod.POST)
public String addSpitterFromForm(#Valid Spitter spitter,
BindingResult bindingResult,
#RequestParam(value="image", required=false)
Accept file upload
 MultipartFile image) {
if(bindingResult.hasErrors()) {
return "spitters/edit";
}
spitterService.saveSpitter(spitter);
try {
if(!image.isEmpty()) {
validateImage(image);
Validate image
 saveImage(spitter.getId() + ".jpg", image); //
}
} catch (ImageUploadException e) {
bindingResult.reject(e.getMessage());
return "spitters/edit";
}
return "redirect:/spitters/" + spitter.getUsername();
}
The client side code
<sf:form method="POST"
modelAttribute="spitter"
enctype="multipart/form-data">
//other stuff
<tr>
<th><sf:label path="fullName">Full name:</sf:label></th>
<td><sf:input path="fullName" size="15" /><br/>
<sf:errors path="fullName" cssClass="error" />
</td>
</tr><tr>
<th><label for="image">Profile image:</label></th>
<td><input name="image" type="file"/>
</tr>
//other stuff
</sf:form>
From the code I am tempted to think that only the input type="file" is sent in a new way. Rest all are sent as key-value pairs. I think the book is also saying the same "When the form is submitted, it’ll be posted as a multipart form where one of the parts contains the image file’s binary data. "
Q2> If what i am thinking is correct, how does client know which input types to send as key-value pairs and whom to send individually?
First of all, enctype of multipart/form-data IS NOT a Spring-MVC thing, it is an attribute of <form> in general web development, which means this attribute can be present in your HTML form regardless the server side technology. You can read more about it here: HTML 5 Candidate Recommendation [Specification] 4 The elements of HTML 4.10 Forms 4.10.22 Form submission 4.10.22.7 Multipart form data, also you can read specifically how the data will be sent by reading RFC2388. If you review it, you will see that data sent in a POST request with multipart/form-data is not a key/value pair anymore, instead it contains multiple parts (yes, it is multi part) where each part looks like this (example belongs to RFC2388):
--AaB03x
content-disposition: form-data; name="field1"
content-type: text/plain;charset=windows-1250
content-transfer-encoding: quoted-printable
Joe owes =80100.
--AaB03x
Note that Joe owes =80100. means Joe owes €100.
You can find another example in HTML 4 Specification where it shows a more concrete example when uploading two or more files (my comments are posted after <--):
Content-Type: multipart/form-data; boundary=AaB03x <-- mark for the whole request
--AaB03x <-- content of a part
Content-Disposition: form-data; name="submit-name" <-- field name
Larry <-- content of the field
--AaB03x <-- content of a part
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=BbC04y
--BbC04y <-- content of a part containing a file
Content-Disposition: file; filename="file1.txt"
Content-Type: text/plain
... contents of file1.txt ...
--BbC04y <-- content of a part containing a file
Content-Disposition: file; filename="file2.gif"
Content-Type: image/gif
Content-Transfer-Encoding: binary
...contents of file2.gif...
--BbC04y-- <-- end of parts containing file
--AaB03x-- <-- end of whole request data

Mime source string to object

I have a standard whole Mime source text string I need converted to either a Java or PHP object (or both if you want to show off !) so it can be manipulated in these platforms.
I have looked everywhere but only seem to be able to create from scratch.
So the below for example becomes an object that I can change headers or body parts, and the resend using the provided classes.
The require application for this is a distributed one, where I can supply customers a small java program while their local email app can point SMTP to, which I have done, and obtained Mime string as below.
I then want to be able to access and manipulate the various parts like headers and individual body parts before sending.
Surely there is some class or library which will offer this ? If necessary I can simply send the string to a PHP script if there is a suitable solution in PHP however its on a shared server so I cannot simply add PHP extensions.
Return-path: <tim#domain_a.com>
Envelope-to: XXXXXXXXXXXX
Delivery-date: Thu, 19 Sep 2013 09:54:17 +0100
Received: from XXXXXXXXXX [61.125]:62344 helo=[192.168.1.10])
by leopard.host-ns.co.uk with esmtpsa (TLSv1:DHE-RSA-CAMELLIA256-SHA:256)
(Exim 4.80.1)
(envelope-from <tXgham#dXm>)
id 1VMa09-000MOc-4T
for tiXham#daXcs.com; Thu, 19 Sep 2013 09:54:17 +0100
Message-ID: <523ABBB6.1080105#datXics.com>
Date: Thu, 19 Sep 2013 09:54:14 +0100
From: Txgham <tiXam#datXics.com>
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20130801 Thunderbird/17.0.8
MIME-Version: 1.0
To: TiXham <tiXam#daXics.com>
Subject: Re: Example
References: <523ABB49.50403#daXnics.com>
In-Reply-To: <523ABB49.50403#daXhanics.com>
Content-Type: multipart/alternative;
boundary="------------000900010104080404030103"
This is a multi-part message in MIME format.
--------------000900010104080404030103
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 7bit
Example showing reply subpart and HTML <apage.html>
On 19/09/2013 09:52, TiXgham wrote:
> Example email
--------------000900010104080404030103
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="Content-Type">
</head>
<body text="#000000" bgcolor="#FFFFFF">
Example showing reply subpart and HTML <br>
<br>
<div class="moz-cite-prefix">On 19/09/2013 09:52, TiXam wrote:<br>
</div>
<blockquote cite="mid:523ABB49.50403#daXanics.com" type="cite">Example
email
<br>
</blockquote>
<br>
</body>
</html>
--------------000900010104080404030103--
This is out of date now and never did fully solve it. The issue was deemed as platform specific (iPhone) and not relevant after so much time.

Navigation with JSF2.0 and Primefaces 3.4

I'm new to JSF and Primefaces and have just started working on logging in and basic navigation and I have run into a problem already. I've gone through about 10 similar questions here on SO and none of the solutions has worked for me yet so I figured I would post up my specific problem so that someone who really knows can point me in the right direction.
Logging in: seems to work just fine as does logging out but I'm concerned because the url in the browser still says that I'm at the login screen after logging in and I used the login example straight from the Oracle EE6 docs. Login method is provided below.
public String login(){
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
try{
logger.log(Level.FINE, "User credentials: name: {0}, password: {1}", new Object[] {this.username, this.password});
request.login(this.username, encrypt(this.password));
logger.log(Level.FINE, "User: {0} logged in", this.username);
}catch(ServletException e){
logger.log(Level.SEVERE, "User: {0} login failed, password: {1}", new Object[]{this.username, encrypt(this.password)});
context.addMessage(null, new FacesMessage("Login Failed!"));
return "error";
}
return "/faces/system/index";
}
After logging in I'm taken to the correct page in the correct directory and everything is being displayed corectly but when you hover over the links the status bar at the bottom of the browser displays the same url for all three links. Code for the page provided below.
<h:body>
<p:layout fullPage="true">
<f:facet name="last">
<h:outputStylesheet library="css" name="discovery.css"></h:outputStylesheet>
</f:facet>
<p:layoutUnit styleClass="headerDiv" position="north" size="100">
<h:graphicImage library="images" name="header.jpg"></h:graphicImage>
</p:layoutUnit>
<p:layoutUnit styleClass="navDiv" position="west" size="200" id="navPanel">
<h:form>
<h:outputText value="Navigation Menu"></h:outputText>
<br/>
<p:commandLink value="First Time Users" update=":main">
<f:setPropertyActionListener target="#{navigationBean.pageToDisplay}" value="tutorial.xhtml"></f:setPropertyActionListener>
</p:commandLink>
<br/>
<p:commandLink value="Help" update=":main">
<f:setPropertyActionListener target="#{navigationBean.pageToDisplay}" value="help.xhtml"></f:setPropertyActionListener>
</p:commandLink>
<br/>
<h:commandLink action="#{loginBean.logout()}" value="Log Out"></h:commandLink>
</h:form>
</p:layoutUnit>
<p:layoutUnit position="center" id="main">
<ui:include src="#{navigationBean.pageToDisplay}"></ui:include>
</p:layoutUnit>
</p:layout>
</h:body>
The NavigationBean
#Named(value = "navigationBean")
#RequestScoped
public class NavigationBean implements Serializable {
public NavigationBean() {
}
public String getPageToDisplay() {
return pageToDisplay;
}
public void setPageToDisplay(String pageToDisplay) {
this.pageToDisplay = pageToDisplay;
}
private String pageToDisplay = "welcome.xhtml";
}
When the page loads after logging in the default page set in the navigation bean is displayed but clicking on any link other than the log out link causes the default page to disappear from the center layout unit and a blank page is displayed/ Clicking on the log out link does log you out like intended though. ANy help would be greatly appreciated.
1. Logging in: seems to work just fine as does logging out but I'm concerned because the url in the browser still says that I'm at the login screen after logging in.
Send a redirect (this instructs the browser to send a new GET request on the given URL, which get reflected in browser's address bar).
return "/faces/system/index?faces-redirect=true";
2. After logging in I'm taken to the correct page in the correct directory and everything is being displayed corectly but when you hover over the links the status bar at the bottom of the browser displays the same url for all three links.
The <h:form> indeed submits to the very same page. Use <h:outputLink> or <h:link> instead of <h:commandLink> for page-to-page navigation. See also When should I use h:outputLink instead of h:commandLink?
3. When the page loads after logging in the default page set in the navigation bean is displayed but clicking on any link other than the log out link causes the default page to disappear from the center layout unit and a blank page is displayed
This is solved by using GET instead of ajax postback for page-to-page navigation. So, it's inherently solved when solving #2. You might only want to redesign your NavigationBean to be a filter or phase listener which also intercepts on GET requests. You shouldn't be navigating by POST at all. It defeats bookmarkability, user experience and SEO, exactly as you're encountering now.

Categories