开发者

Overriding the JSP servlet (filter "*.jsp") to wrap in an authentication model

Can the JSP servlet that filters on *.jsp (org.apache.jasper.servlet.JspServlet in Tomcat 6) be extended in some way so whenever someone goes to a JSP page I can do some server side authentication to check whether the user can view the page. Our current technique is a taglib in a common include that is imported into each JSP page, but it's not very elegant.

The key here is that I don't want to reinvent the wheel and worry about compiling JSPs into Servlets, I would ideally like to delegate in each method with s开发者_运维知识库uper.meth().

I've been searching Google but I don't know the right keywords to use. Anything containing JSP and Servlet returns beginner tutorials.

Thanks,

John


Look at Servlet Filters, and use that Filter before forwarding to some JSP or Servlet.


When not taking benefit of the Java EE provided container managed security, then the normal basic practice is that you store the logged-in User in the session scope and uses a Filter on the desired url-pattern to check if the User is logged in.

Here's a basic example to get the picture:

Login:

User user = userDAO.find(username, password);
if (user != null) {
    session.setAttribute("user", user);
} else {
    // Do your thing to show "Unknown login" error.
}

Filter (which is mapped on an url-pattern of for example /secured/*, /protected/*, etc where in you place the restricted JSP pages expect of the login page):

User user = session.getAttribute("user");
if (user != null) {
    chain.doFilter(request, response); // Logged in, so continue with request.
} else {
    response.sendRedirect("login"); // Not logged in, redirect to login page.
}

Logout:

session.removeAttribute("user");

// Or, a bit too drastically:
session.invalidate();

You can of course also take benefit of what Java EE out of the box provides with regard to security. A commonly used way is the declarative container managed security wherein you can specify users and roles. You just need to declare a <security-constraint> and a <login-config> in the web.xml and configure an user realm in the appserver. The details depends on the appserver used, but if it is for example Tomcat 6.0, then you can find here some documentation about that.


If basic auth isn't sufficient, maybe Spring Security would be better. It's a natural, especially if you're already using Spring. One big advantage is that it's declarative, so you can easily protect URLs just by adding them to security configuration.

Doing this via inheritance would be brittle and require code changes every time you modified your security. Best to have security as a cross-cutting concern.


Can you not create another filter and put it above JspServlet? This filter would check your security stuff and do some handling (e.g. redirect to login page) if something is wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜