Role Based Access Control in Java Web Application Example - onlyxcodes

Saturday 9 March 2019

Role Based Access Control in Java Web Application Example

In this tutorial post, you will see role based access control (RBAC) login in Java. I already have a post article multi-user-based login system in PHP and the three roles admin, user, and employee in this article are login access in a single login form and go to their home page.


In this tutorial, I've implemented the same principle in Java platform language JSP. Role Based Access Control (RBAC) is a security model that assigns restricted permission to one or multiple role-based users in the login system that is mostly used in the single login form.


The RBAC always checks the authentication of the user's email, password and role name in login access time as other users try to access other roles account for some time so RBAC detects appropriate message. Let’s achieved that model in JSP.


Role Based Access Control in Java Web Application Example

Table Content

1. What is HttpSession?

2. Database And Table Creates

3. JSP login Page

    3.1 JSP Login Codes

4. JSP Registration Page

    4.1 JSP Registration Codes

5. admin_home.jsp

6. employee_home.jsp

7. user_home.jsp

8. logout.jsp


1. What is HttpSession?

The webserver stored short memory of the visited user they don't have long-term user activity so you can’t maintain state between the user and webserver. The HttpSession object helps the webserver to store each user's unique session object.


Each user wants to visit once the object holds its activity from the unique session object, shortly the HttpSession object maintains the state between the user and the webserver and uses it to store user details.


2. Database And Table Creates

First, to build a database I used here is 'jsp_multiuser_login_db' called a database, and copy and paste SQL code below to store user fields in your PHPMyAdmin.


See the field of the role that indicates the specific name of the role that users insert.


I've already put a record of admin dumping in the table and this is a super admin. 


--
-- Database: `jsp_multiuser_login_db`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_user`
--

CREATE TABLE `tbl_user` (
  `id` int(11) NOT NULL,
  `firstname` varchar(15) NOT NULL,
  `lastname` varchar(15) NOT NULL,
  `email` varchar(40) NOT NULL,
  `password` varchar(30) NOT NULL,
  `role` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;

--
-- Dumping data for table `tbl_user`
--

INSERT INTO `tbl_user` (`id`, `firstname`, `lastname`, `email`, `password`, `role`) VALUES
(1, 'admin', 'admin', '[email protected]', '123456', 'admin');

3. JSP Login Page

See this page is index.jsp, and this page provides a login form. The form carries two input boxes, and an option to select. The input box that will accept user email, password and select option that will take specific names of roles from user-selected for access to log in.


<form method="post" id="loginForm" class="form-horizontal">
     
    <div class="form-group">
    <label class="col-sm-3 control-label">Email</label>
    <div class="col-sm-6">
    <input type="text" name="txt_email" class="form-control" placeholder="enter email" />
    </div>
    </div>
   
    <div class="form-group">
    <label class="col-sm-3 control-label">Password</label>
    <div class="col-sm-6">
    <input type="password" name="txt_password" class="form-control" placeholder="enter passowrd" />
    </div>
    </div>
   
    <div class="form-group">
    <label class="col-sm-3 control-label">Select Type</label>
    <div class="col-sm-6">
    <select name="txt_role" class="form-control">
        <option value="" selected="selected"> - select role - </option>
        <option value="admin">Admin</option>
        <option value="employee">Employee</option>
        <option value="user">User</option>
    </select>
    </div>
    </div>
    
    <div class="form-group">
    <div class="col-sm-offset-3 col-sm-9 m-t-15">
    <input type="submit" name="btn_login" class="btn btn-success" value="Login">
    </div>
    </div>
    
    <div class="form-group">
    <div class="col-sm-offset-3 col-sm-9 m-t-15">
    You don't have a account register here? <a href="register.jsp"><p class="text-info">Register Account</p></a>  
    </div>
    </div>
     
</form>
 

create login page in jsp

3.1 JSP Login Codes :

When the user fills in all fields and then submits the form, the user's email, password, and unique role name in the database will match under JSP codes.   


If both are present in the table then a session will be launched by selecting a specific role name and allowing the user to access the home page, otherwise, the necessary message will be displayed.


Note – The admin_login, employee_login, and user_login are different names of session objects that happen at the time the session begins according to the selection of the particular role name.  


<%@ page import="java.sql.*" %>

<%
 //check condition admin login not back index.jsp(login) page
 if(session.getAttribute("admin_login")!=null){
  response.sendRedirect("admin/admin_home.jsp");
 }

 //check condition employee login not back index.jsp(login) page
 if(session.getAttribute("employee_login")!=null){
     response.sendRedirect("employee/employee_home.jsp");
 }
 
 //check condition user login not back index.jsp(login) page
 if(session.getAttribute("user_login")!=null){
     response.sendRedirect("user/user_home.jsp");
 }
 
    if(request.getParameter("btn_login")!=null) 
    {
        String email,password,role;
        
        email=request.getParameter("txt_email"); 
        password=request.getParameter("txt_password"); 
        role=request.getParameter("txt_role"); 
        
        String dburl="jdbc:mysql://localhost:3306/jsp_multiuser_login_db"; 
        String dbuname="root";    
        String dbpwd =""; 
        
        try
        {
            Class.forName("com.mysql.jdbc.Driver"); //load driver
            Connection con=DriverManager.getConnection(dburl,dbuname,dbpwd); 
            
            PreparedStatement pstmt=null; 
            
            pstmt=con.prepareStatement("SELECT * FROM tbl_user WHERE email=? AND password=? AND role=? "); 
            pstmt.setString(1,email);
            pstmt.setString(2,password);    
            pstmt.setString(3,role);
            ResultSet rs=pstmt.executeQuery(); 
            
            if(rs.next())
            {
                String dbemail=rs.getString("email");
                String dbpassword=rs.getString("password");     
                String dbrole=rs.getString("role");
                
                if(email.equals(dbemail) && password.equals(dbpassword) && role.equals(dbrole)) 
                {
                    if(dbrole.equals("admin")) 
                    {
                        session.setAttribute("admin_login",dbemail);                         response.sendRedirect("admin/admin_home.jsp"); 
                    }
                    else if(dbrole.equals("employee")) 
                    {
                        session.setAttribute("employee_login",dbemail);                         response.sendRedirect("employee/employee_home.jsp");                     }
                    else if(dbrole.equals("user")) 
                    {
                        session.setAttribute("user_login",dbemail); 
                        response.sendRedirect("user/user_home.jsp"); 
                    }
                }
            }
            else
            {
                request.setAttribute("errorMsg","invalid email or password or role"); 
            }
            
            pstmt.close(); 
            con.close(); 
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
%>

4. JSP Registration Page

This is the register.jsp page which includes the registration form, this form has the same style as the login form and contains four registration fields which are first name, last name, email, password and role name for new users to register in the database. 


Note – The last select role filed option determines the two user and employee role names that are selected based on new users.


<form method="post" id="registerForm" class="form-horizontal">
     
    <div class="form-group">
    <label class="col-sm-3 control-label">Firstname</label>
    <div class="col-sm-6">
    <input type="text" name="txt_firstname" class="form-control" placeholder="enter firstname" />
    </div>
    </div>
                    
    <div class="form-group">
    <label class="col-sm-3 control-label">Lastname</label>
    <div class="col-sm-6">
    <input type="text" name="txt_lastname" class="form-control" placeholder="enter lastname" />
    </div>
    </div>
                    
    <div class="form-group">
    <label class="col-sm-3 control-label">Email</label>
    <div class="col-sm-6">
    <input type="text" name="txt_email" class="form-control" placeholder="enter email" />
    </div>
    </div>
   
    <div class="form-group">
    <label class="col-sm-3 control-label">Password</label>
    <div class="col-sm-6">
    <input type="password" name="txt_password" class="form-control" placeholder="enter passowrd" />
    </div>
    </div>
     
    <div class="form-group">
    <label class="col-sm-3 control-label">Select Type</label>
    <div class="col-sm-6">
    <select class="form-control" name="txt_role">
        <option value="" selected="selected"> - select role - </option>
        <option value="employee">Employee</option>
        <option value="user">User</option>
    </select>
    </div>
    </div>
    
    <div class="form-group">
    <div class="col-sm-offset-3 col-sm-9 m-t-15">
    <input type="submit" name="btn_register" class="btn btn-primary" value="Register">
    </div>
    </div>
   
    <div class="form-group">
    <div class="col-sm-offset-3 col-sm-9 m-t-15">
    You have a account login here? <a href="index.jsp"><p class="text-info">Login Account</p></a>  
    </div>
    </div>
    
</form>

create registration page in jsp

4.1 JSP Registration Codes :

New user fills in all field values and then hint on the register button to register all data in the database below JSP code. And it's responsible for searching database duplicate email values if detected then it will display sorry email already exists message.


<%@page import="java.sql.*"%>

<%
    if(request.getParameter("btn_register")!=null)  
    {
        String firstname,lastname,email,password,role; 
        
        firstname=request.getParameter("txt_firstname"); 
        lastname=request.getParameter("txt_lastname"); 
        email=request.getParameter("txt_email"); 
        password=request.getParameter("txt_password"); 
        role=request.getParameter("txt_role"); 
        
        String dburl="jdbc:mysql://localhost:3306/jsp_multiuser_login_db"; 
        String dbuname="root";    
        String dbpwd =""; 
        
        try
        {
            Class.forName("com.mysql.jdbc.Driver"); 
            Connection con=DriverManager.getConnection(dburl,dbuname,dbpwd); 
            
            PreparedStatement pstmt=null; 
            
            pstmt=con.prepareStatement("SELECT * FROM tbl_user WHERE email=? "); 
            pstmt.setString(1,email); 
            ResultSet rs=pstmt.executeQuery(); 
           
            if(rs.next())
            {
                String checkEmail=rs.getString("email");
                
                if(email.equals(checkEmail))    
                {
                    request.setAttribute("errorMsg", "sorry email already exist"); 
                }
            }
            else
            {
                pstmt=con.prepareStatement("INSERT INTO tbl_user(firstname,lastname,email,password,role) VALUES(?,?,?,?,?)"); 
                pstmt.setString(1,firstname);
                pstmt.setString(2,lastname);
                pstmt.setString(3,email);           
                pstmt.setString(4,password);
                pstmt.setString(5,role);
                pstmt.executeUpdate(); 
                
                request.setAttribute("successMsg", "register successfully please login account"); 
            }
            
            pstmt.close();  
            con.close(); 
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
%>

5. admin_home.jsp

This is the home page of the admin.


Here we get the admin_login session object if it is not found then send a response.sendRedirect() method to the login page. Because the admin role does not access the admin dashboard without session.


<center>
    <h1>Admin Page</h1>
    <%
    response.setHeader("Cache-Control", "no-cache,no-store, must-revalidate");
        
    if(session.getAttribute("admin_login")==null || session.getAttribute("admin_login")=="") 
    {
     response.sendRedirect("../index.jsp"); 
    }
    %>
  
    <h2>Welcome, <%=session.getAttribute("admin_login")%></h2>
    <h3><a href="../logout.jsp">Logout</h3>
        
</center>

admin home page

6. employee_home.jsp

Below see the employee home page.


We use the same admin page condition style, get employee_login session object if session values detect null then send the response.sendRedirect() method to the login page.


<center>
 <h1>Employee Page</h1>
    <%
    response.setHeader("Cache-Control", "no-cache,no-store, must-revalidate");
        
    if(session.getAttribute("employee_login")==null || session.getAttribute("employee_login")=="") 
    {
        response.sendRedirect("../index.jsp"); 
    }
    %>
  
    <h2>Welcome, <%=session.getAttribute("employee_login")%></h2>
    <h3><a href="../logout.jsp">Logout</h3>
        
</center>

employee home page

7. user_home.jsp

Last you can see the user home page.


Again here we use the same approach we get session object user_login if not found then the response.sendRedirect() method sends to index/login page.


<center>
    <h1>User Page</h1>
    <%
    response.setHeader("Cache-Control", "no-cache,no-store, must-revalidate"); 
        
    if(session.getAttribute("user_login")==null || session.getAttribute("user_login")=="") 
    {
         response.sendRedirect("../index.jsp"); 
    }
    %>
  
    <h2>Welcome, <%=session.getAttribute("user_login")%></h2>
    <h3><a href="../logout.jsp">Logout</h3>
        
</center>

user home page

I know you think what the aim of the codes below is to see every homepage of the roles. 


The aim of the codes below successfully logout any role not direct access to the personal account. When they try to use these codes, no user personal account will be shown.


response.setHeader("Cache-Control", "no-cache,no-store, must-revalidate"); 

8. logout.jsp

If the user/role clicks on the hyperlink log out then the method session.invalidate() destroys the session and the method response.sendRedirect() sends to the login page. 


<% 
session.invalidate(); 
response.sendRedirect("index.jsp"); 
%>

Download Codes

4 comments:

  1. R u for real?
    What happens when i want to create a new role?

    ReplyDelete
  2. Replies
    1. end of tutorial click on the download button to download source code zip file

      Delete

Post Bottom Ad