Issue
I have a registration form. On the form submission a new user is created (added to a DB) and is also added to an HttpSession. The user role for a Form based auth is also set automatically when he gets registered. Then the registration servlet forwards the user to a "registrationSuccess.jsp" page. From this page the user may enter a web shop by clicking a link.
However he is forced to login before he's allowed to access the requested page. How can I make it so that the user doesn't have to login after registration? Is it possible to achieve with Form based authentication? As far as I understand, adding a user to an HttpSession is not enough.
The link to the requested page consists of a url pattern that is handled by a servlet. I've added the following code to the servlet to check if the user has been added to the session. But anyway the users are added to the HttpSession right after registration (in the previously mentioned registration servlet). So this code is for users that are not yet added to the session.
Customer customer;
String username = req.getRemoteUser();
if (username != null && req.getSession().getAttribute("myUser") == null) {
// First-time login. You can do your thing here.
customer = customerDao.read(username);
req.getSession().setAttribute("myUser", customer);
}
The registration page ("/registration-customer.jsp"
) is an unprotected resource so all users have access to it. After the user submits the form he gets forwarded to the ("/customer/registrationSuccess.jsp"
) which is a protected path. And he is not required to login which is great. But for some reason when user clicks the link on this page containing a servlet path ("/customer/products"
) he is required to login before getting access to the resource.
Solution
After registration you could:
req.login(username, password);
and then redirect to "/customer/registrationSuccess.jsp"
instead of forwarding to it.
URL protection is not applied to forwarded resources. From §13.2 Declarative Security section of the Java Servlet Specification:
The security model applies to the static content part of the web application and to servlets and filters within the application that are requested by the client. The security model does not apply when a servlet uses the RequestDispatcher to invoke a static resource or servlet using a forward or an include.
Answered By - Steve C