Filter for checking session existence - java

I am developing a web application in Struts. I have a requirement that I have to check that a session exists for user. If the user session exists then user can access the resource, or I need to check session variable existence before accessing every JSP page.
For that I make use of filter where I check for the session variable existence. But when I use filter, every request is routed to that filter--even the login page request is routed to filter. The login page doesn't need the filter check applied, what to do for this?

This is typical session filter use case. For login page request, not to be filtered, you need have a different URL for login page which will be excluded in the URL mapping for the filter.
OR
In the filter itself, you can check what is the requested URL, its login page then don't check for the session. But I would recommend the earlier approach because its rightly address the Separation of Concern philosophy.

Related

Restrict accessing servlet pages directly

I have created a simple login page which in turn redirects to the list of file contents. I do have three separate servlets. LoginServlet, LogoutServlet and FileUploadServlet. Where the Login and Logoutservlet redirects to the main page. But the FileUploadServlet will display the page with the two text fields along with a file upload. When the user type the url with the FileUploadServlet name directly the page loads without logging in. How to restrict accessing this. Please help me.
You could use AuthenticationFilters in web.xml. Please add a filter and write a method to authenticate every request whether it is valid or not.
The session Attributes can be used for validation. Like, during login, the session attributes can be set if credentials are valid, and so when the next request is made, the session attributes can be sent along with the request, which can be used for authenticating it. If the request doesn't have that session attribute, you could just scrap that request.

Session management using spring security

I have created a basic spring security authentication using UserDetailsService and now I am able to validate user. However, I don't understand how to achieve below things:
Once a user is logged in, when next request comes how and where do I check if the request is coming from the same logged in user or other logged in user?
I know the concept of Spring interceptors where I can intercept all incoming request. But is there something in spring security that does this?
How can I start a session after logging in and store values in session for that user?
I browsed through existing answers but most of examples are for logging in.
I would appreciate if someone can give me examples.
EDIT:
I think I should use session scoped beans in order to maintain user's session contents rather than manipulating httpsession directly.
I think you really need to spend some time reading the Spring security documentation and over all JSP, servlet and MVC architecture. You have several misunderstandings,
After authentication, you don't need to start a session it was already there when the request came. Remember request.getSession()we get the session from the request and I am really NOT aware of any other way i.e. instantiating session object and assigning it to request/response. After successful authentication spring automatically sets a SPRING_SECURITY_CONTEXT attribute in session and this variable is later used to determine whether user is already authenticated or not (Spring does that for you, you don't need to use this attribute).
In spring security we set an authentication entry point which has information about login page url and FORM_LOGIN_FILTER which has information about login processing url, login success url and login failure url among few other things.Every request whose session doesn't have SPRING_SECURITY_CONTEXT and auth attribute gets redirected to login page url.
I could give the code directly but it would be great if you read at least few pages of Spring documentation here. Once you understand the concepts and are still not able to solve the problem. Edit your question with detailed problem and we will try to fix it.
At first you need to create an Authentication object using current HttpRequest as below:
public class SessionService{
public Authentication getSession(HttpServletRequest request) {
HttpSession session=request.getSession();
SecurityContext ctx= (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
Authentication auth=ctx.getAuthentication();
return auth;
}
}
Then, you can retrieve the session details from this Authentication object by passing the current HttpRequest as follows:
Authentication auth = sessionService.getSession(request);
The above auth object contains the details that you need.

Access to a static HTML page using servlet sessions

I'm trying to set up access to a static HTML page - lets call it search.html.
I understand I can use cookies for this task, but is it possible with servlet sessions?
What options are there so access is only provided once a user is logged in? I have a login servlet that forwards to search.html however I only want this to be access once a user is logged in and a session is created.
Thanks
When the user logs in you store something in the Session indicating that. This can be as simple as a boolean flag or a full User object with roles etc. Then you write a filter which checks the presence of this flag or the roles of the user etc. Depending on the outcome you either let the reqest through or deny it with 403 Forbidden. Filters can be configured to paths in the web.xml.

Spring Security - Anonymous Authentication - HttpSessionRequestCache

Please help me on this.
void setCreateSessionAllowed(boolean createSessionAllowed)
method of
org.springframework.security.web.savedrequest.HttpSessionRequestCache
class says
If true, indicates that it is permitted to store the target URL and exception information in a new HttpSession (the default). In situations where you do not wish to unnecessarily create HttpSessions - because the user agent will know the failed URL, such as with BASIC or Digest authentication - you may wish to set this property to false.
So I did not understand the description properly, also we are using a product and its documentation says setting it to false will disable the creation of anonymous user sessions.
So my question is, session creation and associating it with a request is servlet container's job. So How come using this method(setCreateSessionAllowed) will not create a session.
Please validate my understanding, is it correct or not. also
setCreateSessionAllowed(false), will JSESSIONID be created or not?
The HttpSessionRequestCache saves the last URL requested by the client in a user session.
This is used by spring security, when it redirects you to a login page, to restore the url after a successful login.
In case of basic or digest authentication is directly authenticated or asked to resend the request with the credentials. Therefore URL caching is not necessary.
If setCreateSessionAllowed is set to true, it will by default create a session to store the last url.
If set to false it will only support this feature if a session is already is created.
If no url is stored, spring security will use the default target URL supplied in the spring security configuration.
As for your last question, it is not directly obvious to me how it will affect the anonymous login feature of your mentions product.

A new HttpSession for each request?

I've always taken for granted the JSESSIONID cookie created for every fresh request for a given client when developing applications using the servlet specification. But after giving it a bit of thought, isn't is more logical for the servlet container to create a cookie header only after the session has been requested and created in code? For clients who have their cookies disabled, won't it end up creating a new HttpSession for each request made?
Please let me know if the question is still unclear so I can edit it. TIA.
A new Session will not be created by the Servlet container by default unless the Servlet actually creates it explicitly. Just because in the Header a JSEESIONID is being populated does not mean that there has to be a seesion on the server. An exception to this is in JSPs that by default create a Session if one is not there unless <%# page session="false" %>
As far as not having cookies turned on:
A web container can use several
methods to associate a session with a
user, all of which involve passing an
identifier between the client and the
server. The identifier can be
maintained on the client as a cookie,
or the web component can include the
identifier in every URL that is
returned to the client.
If your application uses session
objects, you must ensure that session
tracking is enabled by having the
application rewrite URLs whenever the
client turns off cookies. You do this
by calling the response's
encodeURL(URL) method on all URLs
returned by a servlet. This method
includes the session ID in the URL
only if cookies are disabled;
otherwise, it returns the URL
unchanged.

Categories