Create a simple authentication system in Eclipse

Home > Search
  by

This assumes you have created your first dynamic web project in Eclipse.

Let's take an example of a page in your app that you want to secure, so that visitors must provide a username and password to be able to access the page. In this example, the "Sample" page is unsecured, meaning any visitor can go to with the Sample page without having to provide credentials.

 

First, you will want to define a security role in your Java applications web.xml file. In this example, a role named "Authenticated" is created, and the Sample page is protected.

<security-constraint>
  <display-name>SampleConstraint</display-name>
  <web-resource-collection>
    <web-resource-name>Sample</web-resource-name>
    <url-pattern>/Sample</url-pattern>
    <http-method>GET</http-method>
    <http-method>PUT</http-method>
    <http-method>HEAD</http-method>
    <http-method>TRACE</http-method>
    <http-method>POST</http-method>
    <http-method>DELETE</http-method>
    <http-method>OPTIONS</http-method>
  </web-resource-collection>
  <auth-constraint>
    <description>Authenticated</description>
    <role-name>Authenticated</role-name>
  </auth-constraint>
  <user-data-constraint>
    <transport-guarantee>NONE</transport-guarantee>
  </user-data-constraint>
</security-constraint>
 
<login-config>
  <auth-method>BASIC</auth-method>
</login-config>
 
<security-role> 
  <role-name>Authenticated</role-name>
</security-role>

 

Now, when navigating to the Sample page, there will be a prompt to provide a username and password. You will not be able to access the Sample page until you've provided a valid username and password. At this point, we've not yet developed the logic to validate the username and password against an authentication systems, thus the Sample page cannot be accessed.

 

This assumes you can can connect to a database.

Create the login.jsp page that will contain the form where the username and password can be provided.

<form action="/beta/Login" method="post">
  Username : <input type="text" name="username"><br />
  Password : <input type="password" name="password"><br />
  <input type="submit">
</form>

 

 

If you have not yet created a package, in the left panel of Eclipse, expand the Java Resources folder, right click on the src folder, and select New > Package. Give the package a name, such as com.main.servlet and select Finish. Right click on the package and select New > Servlet. Give the servlet a name, such as Login, and select Finish.

Import the following items.

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 

In the doPostmethod section of the markup, add the following.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");
	
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        String user = request.getParameter("username");
        String pass = request.getParameter("password");

        String sql = "select * from authentication where username='" + user + "'";

        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://www.example.com:3306/database_name,"db_username","db_password");
            Statement s = conn.createStatement();
            ResultSet rs = s.executeQuery(sql);
            String un = null;
            String pw = null;
            
            PrintWriter prwr1 = response.getWriter();               
            if(!rs.isBeforeFirst()){
                prwr1.write("<p> No Such User in Database</p>");
            }

            while (rs.next()) {
                un = rs.getString("username");
                pw = rs.getString("password");
            }
                      
            PrintWriter pww = response.getWriter();

            if (un.equalsIgnoreCase(user) && pw.equals(pass)) {
                pww.write("<p>Welcome, " + user + "</p>");
            } else {
                pww.write("<p>The username or password you provided are invalid</p>\n");
            } 
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

}

 

Add the following to your web.xml file.

    <servlet>
        <servlet-name>Login</servlet-name>
        <servlet-class>com.jwt.servlet.Login</servlet-class>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>Login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

 

Run the application in Eclipse, or export the WAR and run the application on an application server. When navigating to index.jsp and providing a valid username and password, text Welcome followed by the provied username should be displayed.



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments