Java JSP Filtering on Query String - java

I have a webpage I am currently building for an internal work tool. It is a sample website that allows a user to login and then execute query from the database. I just implemented a filter to re-direct not-logged in users to the login page. The doFilter function looks like this
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("user") == null) {
// No logged-in user found, so redirect to login page.
response.sendRedirect(request.getContextPath() + "/Login.jsp");
} else {
// Logged-in user found, so just continue request.
chain.doFilter(req, res);
}
}
In my web.xml I have
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>Servlets.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/Home.jsp</url-pattern>
</filter-mapping>
If I access Home.jsp directly it will re-direct to the Login Page. However, once logged in, the user is moved to the Home.jsp page which allows the user to execute a query against the database. The home URL will look like
http://localhost:8084/LiveTrades/Home.jsp
But once they provide input, it will move to a new page displaying the results with url string like
http://localhost:8084/LiveTrades/Request?BIC=cat (assuming the user entered 'cat' for the input 'BIC' field).
If a user inputs this above url directly when not logged not, it will process fine, when it shouldnt. I know this is because my filter is only being invoked from the Home.jsp page. How can I get around this to prevent pages with Request* to be filtered?
Would it be easier to have another jsp page, say Results.jsp, and have the Servlet that processes the information from the database pass the data on to Results.jsp? Then I can simply add Results.jsp to the web.xml.

I managed to solve this problem by re-structuring my webpage. The results are now displayed via a JSP page, the data is passed to the JSP page from a Servlet. Now in my filter I simply add the Result JSP page and problem solved.

Related

Webfilter Java RequestDispatcher affords content of site in the debugger console not a redirecting to

I have a JQUERY call to a servlet. Before the servelt is call, i want to use a filter to check if a user is succeffully signed in:
$.get("Anwender",function(data){
console.log(data);
$.each(data,function(key,value){
[...]
}
[...]
}
My Filter to check if the user is logged in looks like this:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String jwt = httpServletRequest.getHeader("Authorization");
if (jwt != null) {
//Some stuff here
}
else
{
final RequestDispatcher dispatcher = request.getRequestDispatcher("fehler.html");
dispatcher.forward(request, response);
}
}
So if i tries to run the code the else statement is called, but in my debug console i see the content of the fehler.html. Just in the console not at the webbroswer.
And all JS,CSS files are also loaded.
So why i can't see the right html site ?
It looks to me as if:
your JQuery code makes an AJAX call to your webserver
your server returns an html response
The browser receives the text html response in variable data
The browser logs HTML
So client and Server don't match. The Server wants to do "normal HTTP" and redirect a client that's not authenticated. The clients wants to call a Rest Service or something similar and handle the response.
If I were you, I'd change the Server response to an Error with a Status Code 4xx and have the client handle it.

How to manipulate jsp hyperlinks in doGet method inside a Servlet?

I'm new in the Java world. I am trying to develop an ACME Demo using a simple CSV file as a database to validate user names and passwords. I wonder if it is possible to make some hyperlinks on the index.jsp page, which will take you to other jsp pages of the same website if you click them. As far as I know hyperlinks will invoke the doGet method inside the servle, where -in my case- you gonna be redirected to those secure jsp if your credentials are valid of course. So it has worked for just one hyperlink and I would like to make things more dynamic no matter how many links are there??!!
jsp
Content1
<!-- Here I would like to add more links -->
Servlet
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
//response.sendRedirect("login.jsp");
HttpSession session= request.getSession(true);
if ((session.getAttribute("userSession") != null) && (session.getAttribute("userSession").equals(session.getId())))
{
response.sendRedirect("content1.jsp");
// How can my doGet method manage multiple links here?
}
else
{
response.sendRedirect("login.jsp");
}
}
You should use a servlet filter.
A filter is a component that will be invoked for all the requests to a given url-mapping, and/or for all the requests to a given servlet.
The filter can then check if the user is logged in. If he's loged in, it asks the container to proceed, i.e. invoke the target servlet as if there was no filter. If he's not logged in, the filter can return an error, or redirect to a login page, or do whatever it wants.
See http://www.oracle.com/technetwork/java/filters-137243.html for an introduction and examples of servlet filters.

jsp : safe selection menu

I'm new to the use of jsp's, servlets, beans etc ... .
Maybe a strange question, but what is the safest way to make a selection menu in a jsp, to make sure you can't access it directly.
At this moment I have a login system and depending of the "kind" of user I retrieve from the db I send them to a specific jsp depending on the "permissions" they have. On this page they will get a selection of the possibilities they can do.
but if I use something like:
next option
it would be easy to just access these next pages from the outside (not much use for the login system then).
I can use a bean I retrieve from the previous page that I check if it's null (this would be so if you get directly to this page) or something like that.
Any suggestions would be welcome. thx
You can use a Servlet Filter to validate if the user has logged in the system and to verify if the user has the rights to access to this page. An example would be as stated in StackOverflow Servlet-Filters wiki. Posting the relevant code:
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
//session.getAttribute("user") contains the user info in session
if (session == null || session.getAttribute("user") == null) {
// No logged-in user found, so redirect to login page.
response.sendRedirect(request.getContextPath() + "/login");
} else {
// Logged-in user found, so just continue request.
chain.doFilter(req, res);
}
}

Filter called sveral times by Tomcat container

I would like some help in understanding a particular behaviour of java Filters: I wrote a simple Filter which gets all user requests and, if a non-logged user requires a restricted resource, the filter forwards user to the home page. Here is my code:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
HttpServletRequest req = (HttpServletRequest) request;
String uri = req.getRequestURI();
System.out.println("\n\nFILTERING...\n\n");
//Se la risorsa appartiene all'area ristretta e l'utente non รจ
//loggato lo sbatto fuori
if(uri.contains("restricted") && (req.getSession(false) == null || req.getSession(false).getAttribute("user") == null)) {
System.out.println("\n\nCannot access\n\n");
//((HttpServletResponse) response).sendRedirect("/Hotel/index.jsp");
req.getRequestDispatcher("/index.jsp").forward(request, response);
}
else {
// pass the request along the filter chain
System.out.println("\n\nNext step\n\n");
chain.doFilter(request, response);
}
}
And the mapping in the web.xml:
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>mycontroller.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
What it is strange to me is that, if I ask a restricted resource via URL, the doFilter method is called several times before moving to the home (the server logs 'FILTERING... Cannot access' 4,5 times).
I'm using Tomcat 7.
Can someone help me to understand? Thanks a lot
You've mapped the filter on /*. It will thus intercept on every single HTTP request. Not only HTML/JSP pages, but also static resources like CSS, JS and image files. Apparently you've requested a HTML/JSP page which in turn references several CSS, JS and/or image files.
Your check in the filter is also pretty poor. You should rather map the filter on /restricted/*.
<url-pattern>/restricted/*</url-pattern>
Then remove that URI check from the filter's code. If you put those static resources outside that map, e.g. in /static or /resources, etc, then the filter won't be invoked for them.

How to return different responses with a normal and ajax login in spring security 3

I build a custom AuthenticationSuccessHandler so users can login using Ajax aswell use a normal login (for users with javascript disabled). To check if it's an ajax call or normal call I sent an extra request header.
If it is an Ajax call i want to return some different code as on normal request. This results needs to come from a jsp file. I could sent the url back but than the user have to do another request to get the data. How can i read the output of the jsp file from within my code or is this a bad design?
This is how i handle the request.
#Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication auth) throws IOException,
ServletException{
if ("true".equals(request.getHeader("X-Ajax-call"))) {
response.getWriter().print("Output of jsp file should go here?");
response.getWriter().flush();
} else {
defaultHandler.onAuthenticationSuccess(request, response, auth);
}
}
Can't you simply forward the request:
request.getRequestDispatcher("myFile.jsp").forward(request, repsponse);

Categories