Reputation: 34
I am doing up this application using mainly JSP and Tomcat as my server.
I am trying to set up authorization levels whereby certain class of users can do certain stuff(access certain pages like creating new records or searching past records), eg creating new users should only be done by an admin.
What i have done now is to first:
<%
String user = request.getParameter("name");
String pwd = request.getParameter("password");
String sql = "select * from members where name = ? and password = ?";
int role = 0;
// since execute returns an int of 1 or 0, we can use it for our if-else statement
if (BaseDAO.check(sql, user, pwd) != 0) {
session.setAttribute("user", user);
role = BaseDAO.checkRole(sql, user, pwd);
session.setAttribute("role", role);
response.sendRedirect("frameMgr.jsp");
} else {
session.setAttribute("login", 0);
response.sendRedirect("loginPage.jsp");
}
%>
After login is successful, I would then pull the value for role from the database and set it to session attribute. Then later at my createNewUser page, i have this to check if the user is of the assigned role
<%
int role = (Integer) session.getAttribute("role");
// only allow people with admin role to create more accounts
if (role != 5) {
response.sendRedirect("frameContent.jsp"); //back to homepage
}
%>
However i realised that this method is inefficient as i would have to put the check on every page and if there are changes in the future i would have to go page by page to change the code. is there a method to control all the authorization levels on one page alone? rather than having to do this on all my jsp files
Upvotes: 1
Views: 249
Reputation: 1754
Best you can do is to use HTTP filter. Every request going to be validated with your filter. Of course this will only prevent user to access resources(page/images etc.) But it does not serve as authorizer for your methods and user interactions.
@WebFilter("/*")
Every resources@WebFilter("/user/*")
Resources under user folder@WebFilter("/admin/*")
Resources under admin folder@WebFilter("/what/ever/*")
Example:
@WebFilter("/user/*")
public class UserFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse res = (HttpServletResponse) servletResponse;
if (/*Check if user is logged*/) {
filterChain.doFilter(servletRequest, servletResponse);
} else {
res.sendRedirect(req.getContextPath() + "/login.jsp");
}
}
@Override
public void destroy() {
}
}
Upvotes: 1