Showing posts with label Filters. Show all posts
Showing posts with label Filters. Show all posts

27.Role Based Authentication and Authorization Using Filters (MVC)

Saturday, February 5, 2011 Posted by Sudarsan 2 comments
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
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:

22.1. Authorization Filter Example

Sunday, January 23, 2011 Posted by Sudarsan 0 comments
Welcome Back !!!

Here I am going to describe the most important topic related to Java Web, i.e Security.

To authorize a person in a web and serving resources to authorized persons over the web we can use Java Filter technology !!

So have a look at the fallowing Example !!!

Create the directory Structure as shown below !!!

Directory Structure


Then create and write the fallowing Java Resources to run this Application as shown below in the images !!


index.jsp


view.jsp



error.jsp



User.java



FilterDispatcher.java


LoginServlet.java


LogOutServlet


After creating the above pages, run your project and observe how Filter is going to intercept the requests and responses.

Type view.jsp in the browser address bar without Login credientials, the browser will redirect to error.jsp page, since the user does not provided the UserName and Password.

If the user provides the Login Details the browser will redirect to view.jsp page !!
Labels:

22. Simple Filter Example

Posted by Sudarsan 0 comments
In this post we are going to learn how Filter is going to work in Web Applications.

Here I am posting a simple Example about a Filter, so take a look at the fallowing pics !!

Directory Structure



Then create the fallowing JSPs as shown in the below images

index.jsp


view.jsp



Employee.java



FilterDispatcher.java


Now just Execute the project and Observe the Output in Web-Browser !!!

In the Next Post, I am going to demonstrate how filters are used to implement security aspects like Authentication and Authorization, so keep in touch with my blog for latest posts !!!
Labels: