Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to make form based authentication in Java

In this article we will discuss different aspects of form based authentication in web based application.

Authentication is an important part of any secured web based application. In modern web based enterprise applications, authentication is implemented in various ways and form based authentication is one of them.

In modern web based applications, authentication mechanism is implemented in various ways. When we try to access a secured web page, the web container activates the authentication mechanism which is configured. Sometime custom authentication module is implemented as per the application need. And sometime readily available mechanisms are used to expedite the development process.

The web container can specify any of the following authentication mechanism:

  • http based authentication.
  • form based authentication.
  • client certificate based authentication.
  • mutual authentication.
  • digest authentication.

The following picture shows a typical http based authentication:

Basic authentication mechanism

Figure 1: Basic authentication mechanism

The basic authentication process is carried out in the following order:

  • Request goes out from a client to access a protected resource.
  • The web server returns a dialog box asking the username and password.
  • The client then submits the username and password to the server.
  • If the supplied credentials are valid, the server returns the requested resource.

Form Based Authentication

Form based Authentication

Figure 2: Form based Authentication

The above picture explains a typical form based authentication which is used in all web based applications for basic login authentication. Here the following activities are carried out :

  • Request goes out from a client to access a protected resource.
  • If the client is not authenticated, the server redirects the client to the login page.
  • The client submits the login form to the server.
  • If the login succeeds, the server redirects the client to the application resource else the client is redirected to the error page.

Form based authentication is not secured if the communication is not done over SSL. This can expose the username and password if someone intercepts the transmission.

Using Form based Authentication in real time

The following sample jsp file shows the usage of a login form which has two input fields userName and password.

Listing 1: A sample login jsp file

<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean"
	prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html"
	prefix="html"%>

<html:html locale="true">
<head>
<title><bean:message key="file.upload" /></title>
<html:base />
</head>

<body bgcolor="white">
<html:form action="/uploadAction" method="post"
	enctype="multipart/form-data">
	<br />
	<br />
	<table width="100%" border="0" align="center" cellpadding="0"
		cellspacing="0">
		<tr>
			<td align="left"><bean:message key="welcome.msg" /><%=request.getSession().getAttribute("NAME")%>
			</td>
			<td align="right"><html:link page="/menu.jsp">
				<bean:message key="menu.link" />
			</html:link></td>
			<td align="right"><html:link page="">
				<bean:message key="logoff.link" />
			</html:link></td>
		</tr>
	</table>
	<hr />
	<table border="0" cellspacing="0" cellpadding="0" width="100%">
		<tr bgcolor="#eaeac8">
			<td align="center"><font size="5"><bean:message
				key="file.upload" /></font></td>
		</tr>
	</table>
	<table align="center" border="0" cellspacing="0" cellpadding="0"
		width="70%">
		<tr>
			<td align="right"><bean:message key="first.file" /></td>
			<td>  </td>
			<td align="left"><html:file property="filePath1" /></td>
		</tr>
		<tr>
			<td align="right"><bean:message key="second.file" /></td>
			<td>  </td>
			<td align="left"><html:file property="filePath2" /></td>
		</tr>
		<tr>
			<td align="right"><bean:message key="third.file" /></td>
			<td>  </td>
			<td align="left"><html:file property="filePath3" /></td>
		</tr>
		<tr>
			<td align="right"><html:submit>Upload</html:submit></td>
			<td>  </td>
			<td align="left"><html:cancel>Cancel</html:cancel></td>
		</tr>
	</table>
</html:form>
<body>
</html:html>

The above jsp file is a struts based login form which has two input fields: userName and password. We all know that in struts the application flow is controlled by the deployment descriptor file: struts.xml.

Listing 2: struts.xml file

<?xml version = "1.0" encoding = "ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC " -//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
	<form-beans>
		<form-bean name = "LoginForm" type = "com.home.upload.action.forms.LoginForm" />
		<form-bean name = "MenuForm" type = "com.home.upload.action.forms.MenuForm" />
		<form-bean name = "UploadForm" type = "com.home.upload.action.forms.UploadForm" />
	</form-beans>
	<global-forwards />
	<action-mappings>
		<action path = "/login" type = "com.home.upload.action.LoginAction" name = "LoginForm" input = "/login.jsp" >
			<forward name = "success" path = "/menu.jsp" />
			<forward name = "failure" path = "/loginFailure.jsp" />
		</action>
		<action path = "/menuAction" type = "com.home.upload.action.MenuAction" name = "MenuForm" input = "/menu.jsp" parameter = "method" >
			<forward name = "upload" path = "/fileUpload.jsp" />
			<forward name = "listFiles" path ="/listUploadedFiles.jsp" />
		</action>
		<action path = "/uploadAction" type = "com.home.upload.action.FileUploadAction" name ="UploadForm" input ="/fileUpload.jsp" >
			<forward name ="uploadSuccess" path ="/uploadSuccess.jsp" />
		</action>
	</action-mappings>
	<message-resources parameter = "ApplicationResources" />
	<plug-in className = "org.apache.struts.validator.ValidatorPlugIn" >
		<set-property property = "pathnames"
			value = "/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" />
	</plug-in>
</struts-config>

We know that in struts the flow of the application is defined in the struts.xml which is the deployment descriptor of the framework. In the given example the name of the form is login which is mapped to a java bean class: LoginAction in the struts.xml file. This class has the field’s userName and password fields and their corresponding getters and setters. The action class is listed below:

Listing 3: LoginForm.java class

package com.home.upload.action.forms;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.ValidatorForm;

public class LoginForm extends ValidatorForm{
    
    /**
     * The serial Version UID.
     */
    private static final long serialVersionUID = 1L;
    /**
     * The user name.
     */
    private String userName = null;
    /**
     * The password.
     */
    private String password = null;
    
    /**
     * @return the userName
     */
    public String getUserName() {
        return userName;
    }
    
    /**
     * @param userName
     *            the userName to set
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }
    
    /**
     * @param password
     *            the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }
    
    /**
     * The reset method.
     */
    public void reset(ActionMapping mapping, HttpServletRequest request) {
        this.userName = null;
        this.password = null;
    }
}

The fields defined in this action form class are directly mapped with the fields in the JSP file. Once these fields are filled and the user hits the submit button, an instance of this action form class gets populate with the values supplied by the user. The instance is then available in the action class which is the servlet class. The action class checks these values for their genuineness and reverts back in the form of action forward. This action forward consists of instructions. These instructions are again mapped in the struts.xml file. The action class is listed as under :

Listing 4: Login Action Class

package com.home.upload.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.home.upload.action.forms.LoginForm;
import com.home.upload.util.UploadConstants;

public class LoginAction extends Action {
    
    private static Logger logger = Logger.getLogger(LoginAction.class);
    
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException {
        
        String target = new String(UploadConstants.SUCCESS);
        if (form != null) {
            LoginForm lForm = (LoginForm) form;
            String uName = lForm.getUserName();
            String pasWd = lForm.getPassword();
            logger.info("uName " + uName);
            if ((uName == null) || (uName.length() == 0)) {
                target = new String(UploadConstants.FAILURE);
            } else if (!(uName.equalsIgnoreCase(pasWd))) {
                target = new String(UploadConstants.FAILURE);
            } else {
                request.getSession().setAttribute("NAME", uName);
            }
        }
        
        return (mapping.findForward(target));
    }
    
}

Conclusion

To conclude lets revisit what we discussed above in the following bullets:

  • Form based authentication is an important aspect of modern applications.
  • It is advised to use the SSL channel for communication in form based authentications.

Hope you liked the article, see you next time.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login