You do not redirect to a login page when using the container-managed security system configured by web.xml.
The J2EE container security system does what its name says: if a user requests a secured URL, the container checks to see if the user is authenticated (logged in). If not, the container presents and processes the login/loginfail forms. If (and ONLY if) the user passes authentication, the original URL request is resumed. No application logic is involved, and no redirection is done. Once the user has authenticated, the original URL request is processed just as if the login wasn't there. In fact, there's not even a "login event" that can be monitored. The only real way for application code to tell that a login occurred is to note that a UserPrincipal object now exists in the incoming HttpServlet requests, because the login process is totally transparent to the webapp.
AJAX makes things a lot stickier, since AJAX implies partial page update, which is incompatible with presentation and processing of a stand-alone login form.
Unfortunately, you cannot simply check roles, since the roles are determined by the login, and if you want to avoid problems with AJAX, that means no login in the AJAX code. That means that the AJAX code must either use an alternative security option OR the page containing the AJAX client code must only be presented AFTER a primary login. Which is generally the preferable way, although with AJAX, there's always the risk of the page staying on the client unattended until the session logs out and the AJAX code fails anyway. You MAY be able to handle this by putting some sort of hidden or meta-data in your login page that the AJAX client can inspect, but there's no "cookie cutter" solution I know of.
If you have a page that is normally unsecured, but offers additional functionality to authenticated users, you should consider rendering the page to be aware of the user authentication state so that the AJAX requests will fail with an alert to the user. If that isn't possible, about the best you can so is forgo role-based access control on the AJAX servlets and make them handle their own security. Or better yet, front them with a servletfilter. Something that will render your "403" page when the user isn't logged in (userPrincipal and remoteUser objects are null).
An IDE is no substitute for an Intelligent Developer.
Joined: Aug 18, 2010
This ajax calls are made in an authetnicated page. I'm looking into this for when the session times out. the idea is that i would refresh the entire page if user gets a 403, requiring the user to login.
I tried to check for roles from a servlet that does nto fall under the security-constraint and as you pointed out it didn't work. I was going to return the 403 if a custom user session object is null.