27.Role Based Authentication and Authorization Using Filters (MVC)
Saturday, February 5, 2011
In this post we are going to learn how Filters are used to implement Authentication and Authorization in web applications.
For this, here I am providing resources to achieve Role Based Navigation example to illustrate Authentication and Authorization.
So have a look at the fallowing images to get clear idea what we need to do here !!
If the user provides proper credentials, the application will navigates to either admin.jsp page or to customer.jsp page.
admin.jsp
customer.jsp
If the user tries to navigate to admin.jsp without providing login details i.e Changing the URL to admin.jsp or customer.jsp in Address bar of the browser the application will display error.jsp page with the fallowing message as shown in the below picture.
To achieve the above functionality in web application create the directory structure as shown below.
Now then create the JSPs and Servlets as shown in the directory structure.Here I am providing the code which I have written in the JSPs in the form of images, so go through the below images.
index.jsp
admin.jsp
customer.jsp
error.jsp
Now write the code for LoginServlet, LogOutServlet, Login and FilterDispatcher.
Here I am providing the code for the above mentioned java classes.
LoginServlet.java
FilterDispatcher.java
LogOutServlet.java
Login.java
When we run the above project, we can observe the anticipated output.
For this, here I am providing resources to achieve Role Based Navigation example to illustrate Authentication and Authorization.
So have a look at the fallowing images to get clear idea what we need to do here !!
If the user provides proper credentials, the application will navigates to either admin.jsp page or to customer.jsp page.
admin.jsp
customer.jsp
If the user tries to navigate to admin.jsp without providing login details i.e Changing the URL to admin.jsp or customer.jsp in Address bar of the browser the application will display error.jsp page with the fallowing message as shown in the below picture.
To achieve the above functionality in web application create the directory structure as shown below.
Now then create the JSPs and Servlets as shown in the directory structure.Here I am providing the code which I have written in the JSPs in the form of images, so go through the below images.
index.jsp
admin.jsp
customer.jsp
error.jsp
Now write the code for LoginServlet, LogOutServlet, Login and FilterDispatcher.
Here I am providing the code for the above mentioned java classes.
LoginServlet.java
public class LoginServlet extends HttpServlet { @Resource private javax.transaction.UserTransaction utx; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String username = request.getParameter("username"); String password = request.getParameter("password"); HttpSession session = request.getSession(); Context ctx = (Context) new InitialContext().lookup("java:comp/env"); utx.begin(); EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName"); Login login = em.find(Login.class, username); if (login == null) { request.setAttribute("notok", "Invalid Username/Password !"); RequestDispatcher view = request.getRequestDispatcher("/index.jsp"); view.forward(request, response); return;} if (login.getPassword().equals(password)) { if (login.getUserrole().equalsIgnoreCase("admin")) { session.setAttribute("login", login); RequestDispatcher view = request.getRequestDispatcher("/admin.jsp"); view.forward(request, response); } else if (login.getUserrole().equalsIgnoreCase("customer")) { session.setAttribute("login", login); RequestDispatcher view = request.getRequestDispatcher("/customer.jsp"); view.forward(request, response); }} else { request.setAttribute("notok", "Invalid Username/Password !"); RequestDispatcher view = request.getRequestDispatcher("/login.jsp"); view.forward(request, response); return; } utx.commit(); } catch (Exception e) { out.print(e); } finally { out.close(); } }
FilterDispatcher.java
package com.controller; import com.model.Login; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FilterDispatcher implements Filter { private FilterConfig filterConfig = null; public FilterDispatcher() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req=(HttpServletRequest) request; HttpServletResponse res=(HttpServletResponse) response; String uri=req.getRequestURI(); HttpSession session=req.getSession(); if(uri.equals("/LoginApplication/admin.jsp")|| uri.equals ("/LoginApplication/customer.jsp")) { Login ob=(Login) session.getAttribute("login"); if(ob==null) { res.sendRedirect("error.jsp"); return; } } chain.doFilter(request, response); } public void destroy() { } public void init(FilterConfig filterConfig) { this.filterConfig = filterConfig; } }
LogOutServlet.java
public class LogOutServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { request.getSession().invalidate(); RequestDispatcher view=request.getRequestDispatcher("/index.jsp"); view.forward(request, response); } catch(Exception e) { out.print(e); } finally { out.close(); } }
Login.java
package com.model;import java.io.*;import javax.persistence.*; @Entity @Table(name = "LOGIN") @NamedQueries({@NamedQuery(name = "Login.findAll", query = "SELECT l FROM Login l"), @NamedQuery(name = "Login.findByUsername", query = "SELECT l FROM Login l WHERE l.username = :username"), @NamedQuery(name = "Login.findByPassword", query = "SELECT l FROM Login l WHERE l.password = :password"), @NamedQuery(name = "Login.findByUserrole", query = "SELECT l FROM Login l WHERE l.userrole = :userrole")}) public class Login implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "USERNAME") private String username; @Column(name = "PASSWORD") private String password; @Column(name = "USERROLE") private String userrole; public Login() { } public Login(String username) { this.username = username; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUserrole() { return userrole; } public void setUserrole(String userrole) { this.userrole = userrole; } @Override public int hashCode() { int hash = 0; hash += (username != null ? username.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Login)) { return false; } Login other = (Login) object; if ((this.username == null && other.username != null) || (this.username != null && !this.username.equals(other.username))) { return false; } return true; } @Override public String toString() { return "com.model.Login[username=" + username + "]"; } }
When we run the above project, we can observe the anticipated output.
Labels:
Filters
hi
this is guptha can you post the topic like how to deploy window base applications and web base applications
thank u
hi sir
we want to learn frame works like spring mvc ,struts and hibernate.
we learn from you more. we wish to learn frame works also
thank u