Block the user request from URL - java

I need to implement a logic in my project to block the user request from the URL bar, let say user is in middle of one module and user wants to resubmit / refresh the page, in normal web applications user can Go to URL bar press enter. But in my project we need to block the user to send the request from URL bar and redirect the page to Page / Session Expired page .
I think we can achieve this by using a servlet filter by checking the request , whether the request is coming from URL bar or a form. Is there any way to check where the request is coming from ?

Use any Random Token Number generated with URL request and every time validate the token.

Just apply authentication filter to restrict access to other pages,if user try access the unwanted page make him land on your desired page.

Related

On refresh browser go to last finished step using cookies(java + react)

Ok, so I have simple website which force user to start from last finished step. Whenever user refresh page he needs to call at application initialization to:
REST /user/{id}/step
This endpoint will tell where user finished. The problem is I am using http only cookie. So I cannot get this {ID} from cookie in javascript.
At the moment I have added additional cookie(NOT http only) named clientId. So application can get his id from cookie, and call to this particular endpoint.
It is working but I feel that it is kinda not best approach. It has few side effects like taking care of clearing this stupid cookie on logout, etc situations.
What is best practice ? I've been thinking about creating additional endpoint which will be used on every application initialization
REST /user/status
// I want to be restfull, so I dont want REST user/logged/step
which will return setCookie clientId="" or setCookie clientId={ID} whenever user is logged or not, in this case I even don't need to care about clearing cookies on frontend side, any ideas?
The problem is I am using http only cookie.
So this http only cookie contains what? I presume a user's session? Then why do you need to specify this user ID in the URL if you should be able to get the ID from the session token?
I believe you should just have the following endpoint REST /user/step which returns the step number for a current user (defined by the session token in the http only cookie) or it returns 401 code (Unauthorised) if the user is not logged in..

Tomcat FORM-based authentication loads ajax content without page wrapper after session timeout

Java application is loading raw ajax data after the session has timeout and the user logs back in.
Scenario:
User logs in successfully
Application loads and sits idle for the session timeout period
User selects an option that is an ajax call to refresh page content
Since the timeout period has passed, the user is redirected to the FORM-based login page defined in the WEB.XML file
User again logs in successfully
Problem starts here: Since the last URL request was for an ajax call, the page loads with the raw content without the full HTML page wrapper
Question: Since Tomcat is handling the Login and session creation process -
How can I handle this situation by either sending back a complete HTML page with the request or just send the user to the application landing page?
I was hoping for a more elegant solution, but here's what I did to solve my issue.
At the top of my servlet controller I added the following code. If the sessions variable "FirstTimeIn" is null I know the user just logged in. I then check to see if the userPath is "/ajaxCall". I use this to identify all my ajax requests. If the userPath is "/ajaxCall", I then redirect the user to the landing page of my web application.
if (session.getAttribute("FirstTimeIn") == null) {
session.setAttribute("FirstTimeIn", "No");
if (userPath.equals("/ajaxCall")) {
response.sendRedirect("sc?action=dashboard");
}
}

response.sendRedirect Vs getRequestDispatcher

I have a servlet, called 'insert' that inserts data in a db.
At the end of this servlet I have a getRequestDispatcher that sends the user to a page called 'outcome.jsp'. My servlet send also a variable to outcome.jsp with request.setAttribute("Message", "bla bla bla");
In outcome.jsp i have a request.getAttribute("Message"); and i show to the user the value of Message.
On the browser url there's always the url of my servlet (http://www.site.com/insert), so the user could use the reload button of the browser and makes the insert 1000000000 times.
I tried using response.sendRedirect but i cant use request.setAttribute, and i need it to show message about the insert outcome
How can i avoid the url of my servlet is shown on the browser url in order not to allow user to make infinite inserts by using the reload button?
Thank you
Which ever of the two methods you use you will still have the same problem (Even in the case of sendRedirect() by capturing and reproducing the request header by the user ). The check of double inserting should be done separately.
Usually, if you want to disable a double entry from a client, you can create a token and send it to the client. When the client wants to make an insert, you can check if this token is valid and then do the insert (AND then remove token from the valid list).
That is just one of many ways....
Hope this helps
If use response.sendRedirect(), a new request will start so you can not access the data you set for your previous request, to show the data you have to use the query parameter, that will append to URl
response.sendRedirect("/outcome.jsp?Message=bla bla")
In your jsp page you need to read as
request.getParameter("Message")

How can I check for authorization in JAAS during request

I have implemented form authentication as offered by JAAS. Since I process all my pages as templates code has to be evaluated every time. Thus when the user is directo to /login the doGet request has to handle it and process the login template.
Now I would like to redirect to the main page after the login was successful. When the user chooses /login again he/she should be redirected to the main page.
Thus I need to know during a doGet request whether the user is authorized, maybe also which authentication. How can I check? Or is this idiom wrong?
Or is this done by request.isUserInRole(String role)? Since it does both, authentication AND authorization?
You can check if an user is logged in by checking if HttpServletRequest#getRemoteUser() (the user name) or #getUserPrincipal() (the associated Princpal object) does not return null.
So, e.g. in doGet() of the /login servlet you could do this:
if (request.getRemoteUser() != null) {
// Already logged in, so redirect to some main page.
response.sendRedirect(request.getContextPath() + "/main");
return;
}
// ...
The #isUserInRole() only checks if the logged-in user has some specific role and this is usually only useful to restrict some pages or page sections for specific roles. So unless you've a general role which is shared by every user, this isn't useful.
You may only want to add a message to inform the enduser why s/he is been redirected and what's the proper way to login again as another user. E.g. "You are already logged in. If you need to login as another user, please go to logout page first." or so in the main page which is conditionally displayed based on some redirect parameter.

Java Servlet redirecting from one Servlet to another and then back to the initial Servlet

I had a question about Java Servlets.
lets say I am on a servlet webpage, 'somePage'. I want to log in (using another servlet, 'login' servlet). So i click on the log-in link on the 'somePage' and get redirected to the 'login' page. I type in my name and password and they are both correct. the login page has successfully logged me in.
(now asking about coding for the 'login' servlet) How do I code the 'login' page so that it will redirect the successfully logged in person back to the, 'somePage' webpage?
Main Question: How does the login page know the page which initially redirected to it is the 'somePage' page?
I have checed out a lot of the request parameters, but non tell me, yes, you were directed from page, 'somePage'. These are the the paramater i have looked at:
String authType = request.getAuthType();
String pathInfo = request.getPathInfo();
String pathTranslated = request.getPathTranslated();
String getUserName = request.getRemoteUser();
String remoteAdd = request.getRemoteAddr();
String uriString = request.getRequestURI();
String sessionID = request.getRequestedSessionId();
String serverName = request.getServerName();
Integer serverPort = request.getServerPort();
String servletPath = request.getServletPath();
I know some of these are obvously not going to give me the answer I am looking for, but I figure one of the HttpServletRequest parameters has got to tell the login page who asked for it to be displayed. Any help would be greatly appreciated. I'm going to continue my search for the answer. I've tried to search for this question, but haven't found an answer.
Instead implementing yourself you should consider using form based authentification for your web app.
Almost every servlet container supports this.
At first you have to configure security. This depends on your application server. I.e. with Jetty you can use a database approach with tables for users and their roles or LDAP, etc.
In web.xml you turn on form based authentification:
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/logon.jsp</form-login-page>
<form-error-page>/logonError.jsp</form-error-page>
</form-login-config>
</login-config>
You specify two JSP pages you have to provide. logon.jsp is the login page for inserting user name and password. logonError.jsp is shown, if user name and password are invalid.
The whole login workflow is handled by the application server.
If the user first goes to a protected URL, the application server presents the login page instead. As a convention the input fields for user name and passwort should be named j_username and j_password. When the user submits the login form the server checks, if the user crendentials are valid (according to its configuration). If so the user is redirected to the original page. Otherwise the login error page is shown.
If you really want to implement it yourself then you can implement a servlet filter so that all calls to protected resources have to pass your filter.
In your filter you can check, if there is already a session present and if the user has successfully logged in. Then the normal call can proceed. Otherwise you can forward to your login page and store the original URL in the session. After a successfull login you can read the original URL out of your session context and redirect to the page the user wanted to see in the first place.
There are different ways of doing this. One way is to have your login page support a continue CGI parameter that gives the URL to which to redirect after the login is successful. Another way to do this is to use the "Referer" header that was passed to the login page, and redirect to that URL.
For the former, you can use ServletRequest.getParameterMap() to get the CGI arguments and determine if there is a CGI parameter named continue (or whatever name you choose to give to that CGI parameter); for the latter, you can use HttpServletRequest.getHeader() to get the "Referer" header.

Categories