We help IT Professionals succeed at work.

How to authenticate user in every JSP page?

pleasure
pleasure asked
on
I'm doing a project using JSP and Servlet. User need to enter their user id and password before they can use my application. In this project, there is number of JSP Pages and Servlets. The access right to thise pages or servlet is based on user access right which is stored in database.

Therefore, before user request to view any pages, I need to verify that the user has log in and determine that the user has the right to view the page. As i said before, user access right is stored in the database.

Is anybody has any idea how to implement this?? I'm thinking to write a function which will do all the verification process, but my problem is how can i call this function from my JSP pages and servlet??

thanks..
Comment
Watch Question

One approach:

Write a class/classes which describes in full the access rights associated with any user (user type, application entitlements etc).  For the sake of argument let's call this class UserPrivilege

When the user logs in, retrieve the access rights from the database, create an instance of UserPrivilege, populated with the user specific details and put it into the session.

Write a method or methods on UserPrivilege which allow a web component (JSP or servlet) to inquire whether the current user has access to execute this page.  Each page will have to know what privileges are needed by users in order for the user to be allowed to execute it.

At the start of each JSP/servlet, retreive the UserPrivilege object from the session, call the appropriate method and take the appropriate action (forward to an error page, for example).

Here's a concrete simple example:

A simpe userprivilege class:

public class UserPrivilege {

     private int userLevel;

     public UserPrivilege(int userLevel) {
          this.userLevel = userLevel;
     }

     public boolean isAllowed(int requiredLevel) {
          return userLevel >= requiredLevel);
     }

}


When the user logs in:

request.getSession().setAttribute("userPrivilige", new UserPrivilege(/*retrieve level from database */2));


On every JSP/ Servlet:

UserPrivilege p = (UserPriviliege) request.getSession().getAttribute("userPrivilege");
if (!p.isAllowed(/* page specific priviliege*/ 1) {
     //forward to error page...
}
//rest of jsp / servlet

The same code will appear on every page, you could write a static function available from every JSP / Servlet which could simplify this.  Just pass in the UserPrivilege object and the level required.

A much better approach is to use a model 2 architecture, where all requests are received by the web app at a single point (controller).  The controller decides whether access should be allowed and forwards to the appropriate JSP or servlet.  But my solution is fine for your needs....


Author

Commented:
thanks for the response.. give me some time to test your approach..i'll be back soon...:)

BRONZE EXPERT
Distinguished Expert 2019

Commented:
 A similar approach to what skinsella has described is to use url-rewritting. Everytime the user changes page you can pass the session information within the URL. To obtain this you can use the encodeURL of the Response object.

  session.setAttribute(<key>, <value>);
  response.encodeURL(<the page you want to go>);

  When you move to the next page you can do a

  session.getAttribute(<key>) and you will get the object you set in the previous page.

Commented:
Use Filters!!!  They are easies way to do any kind of permission/authentication of various levels on any number of servlets/jsps

http://java.sun.com/products/servlet/Filters.html
http://www.javaworld.com/javaworld/jw-06-2001/jw-0622-filters.html

a combination of your web.xml and a filter for each level will make this much easier.  Then you don't need to modify any of your servlets.. the authentication is handled separately.

CJ

Commented:
Hi,
  what they are telling is absolutely correct...

Here is the simple version of the above.

  when u r authenticating the username and password, get the user rights also.

   Store the username and rights in the session

   In all the jsp/servlets get the session value and rights value and try to authenticate the userrights as u r wish.

GoodLuck
VasanS
Make it a little easier on yourself by using a base servlet that does the authentication, and then passes the request/response to each subclass for specific handling.

Commented:
Thats what a FILTER does.

Trust me it is the ideal solution for any kind of authentication.

Your filter will check the permissions and if the user is fine send them to the Servlet they are requesting.

the way you invoke filters is as simple as adding the URL you want filtered add this to your web.xml:
<filter-mapping url-pattern="/account/*" filter-name="com.yourcompany.security.SecurityFilter" />

in your SecurityFilter.java you check the login credentials and allow or deny access accordingly.

Simple as that.. no passing of attributes, nothing.

CJ

Author

Commented:
cheekycj:
In order to use Filter, do I need to install anything? Currently i'm using JRun.
FYI, i'm quite new in this field.

vasan_sr:
I can't store user rights in session cause my user rights is store in database. When user requested a JSP/Servlet, I intend to pass user id and a code representing the JSP/Servlet to the function. The function will do the authentication base on the user id and the code. Before that, the function will also need to verify either the user had log in by checking the session like below

if (session.getAttribute("UserID") == null){

}

Author

Commented:
cheekycj:
In order to use Filter, do I need to install anything? Currently i'm using JRun.
FYI, i'm quite new in this field.

vasan_sr:
I can't store user rights in session cause my user rights is store in database. When user requested a JSP/Servlet, I intend to pass user id and a code representing the JSP/Servlet to the function. The function will do the authentication base on the user id and the code. Before that, the function will also need to verify either the user had log in by checking the session like below

if (session.getAttribute("UserID") == null){
   return false
}

thanks
Once you get the login info from your database, why cant you cache this information?

Commented:
filters are a part of the Servlet 2.3 spec.  If your version of JRUN supports Servlet 2.3 and JSP 1.2 you should be fine to use them.

CJ

Author

Commented:
m_onkey_boy :
yupe..i can cache the info, but if i assigned task A to a user after he/she has log in, he/she will not be able to access task A until he/she log in again to the system. Beside, if i store user right into session, my data is quite large. i'm worry that it'll affect my system perfomance if i store in session.

cheekycj :
My JRUN is running with Servlet 2.2 and JSP 1.1, can i download Servlet 2.3 and JSP 1.2? where can i download?? is it free??

thanks
Commented:
actually for filters you just need servlet 2.3 not the JSP 1.2  -plus JSP1.2 needs to implemented by the servlet engine itself where as servlet 2.3 is just updating a jar.

the current jar is in :
/Alliare/JRun/lib/ext/servlet.jar
Rename it to servlet-old.jar (in case the update doesn't work you can go back to this one)

Now you need to download the JSDK jar from Sun:
http://java.sun.com/j2ee/sdk_1.3/
This will install at your c:\jsdk directory.

Now there should be a servlet.jar (or possibly jsdk.jar).

Copy this over to the  /Alliare/JRun/lib/ext/ directory as servlet.jar.

Now you should be able to use Servlet 2.3 filters.

CJ
I think the topic has side-stepped a little.

My code (2nd post) or similar can be used whichever mechanism is chosen (servlet base class, filters, modification of every JSP/servlet). Downloading the latest servlet API (for filters) will not give you an out-of-the box solution, just make it easier to include the code on every request...

Commented:
Filters are a more robust approach to authentication.

Yes the authentication logic needs to be coded but filters allow you to apply an authentication framework to almost any application without modifying the application itself.

So you write a security filter and just apply it to any of the applications/servlets/jsps without having to modify any of those.

Nothing is out of the box but good design is what keeps maintenance down.

CJ

Author

Commented:
skin:
I had try your method and I hit several problems. Is it the session variable is shared among the servlet and JSP?
cause when i set the session value in a JSP, my servlet couldn't get the value. For example, when i log out, i set the session to "" as follow

session.setAttribute("UserID",""),

but when i go to my servlet i still can get the value for request.getSession().getAttribute("UserID") which is the previous id i used..

is there any method for me to kill the session when i log out..

your guide is urgently needed..please help..
thanks a lot..

CJ :
i already downloaded the JSDK jar, but is it free?? I'll actually try both approach and determine which one suit me most...

thanks

Call invalidate() on the Session object to invalidate it and remove all session variables (i.e. when the user logs out) i.e.

request.getSession().invalidate()

There is one session object per "logged in" user of the web application.  It is shared between JSPs and servlets but will only work if you have cookies enabled in your browser (see URL rewriting if cookies are disabled).

You should not experience the behaviour you did regarding the session variable not being set, perhaps it was mis-spelt (case sensitivity) in your code....

Author

Commented:
I cannot use request.getSession().invalidate() in jsp file, it'll return me " Session is invalid ". Everytime a user log out my system will redirect them to login page where in this page, I'll destroy the session but "request.getSession().invalidate() " seem like does not work in JSP, what is the function to destroy session in a JSP file???

thanks again...
 

Author

Commented:
I cannot use request.getSession().invalidate() in jsp file, it'll return me " Session is invalid ". Everytime a user log out my system will redirect them to login page where in this page, I'll destroy the session but "request.getSession().invalidate() " seem like does not work in JSP, what is the function to destroy session in a JSP file???

thanks again...
 

Author

Commented:
hi experts,
I guest the problem is rely on the Temporaty Internet Files or the History in Internet Explorer, I suspect everytime I refresh my page, Internet Explorer didn't get if from server but from it's cache. If this is really the problem, is there anyway for me to force the browser to get the latest files from server instead of from it's cache, or may be u guys can give me so tips on how to handle this??

thanks

Commented:
Yes, the SUN JSDK is free.

CJ