How to implement Form based authentication with struts2

10,295

You will have to provide username and password combination that corresponds to a user who has already been created in the file realm of the GlassFish Server and has been assigned to the group of manager.

Here is a link on how to create a File realm.

Here is a link on how to create a jdbc security realm.

Here is a working example. You can check if it matches with your code.

Here is a link to better understand form-based authentication.

Hope this helps. :)

EDIT:

The idea behind form based authentication is that you write a JSP or Servlet that presents a form with the following fields and action:

<form action="j_security_check" method="post">
    <input type="text" name="j_username"/>
    <input type="password" name="j_password"/>
    <input type="submit"/>
</form>

When the form is submitted, the servlet container checks the credentials for you using the mechanism you've defined (e.g. JAAS). In your web.xml, you set the following:

<login-config>
    <form-login-check>
        <form-login-page>/login.jsp</form-login-page>
        <form-error-page>/error.jsp</form-error-page>
    </form-login-check>
</login-config>

This allows the container to locate the JSP or Servlet containing your form, or your error handling code.

Share:
10,295

Related videos on Youtube

codeofnode
Author by

codeofnode

Day : Coding for network management software. Eve: Workout to keep my body and mind fit Night: For templist, allrounder and my other open source projects

Updated on June 04, 2022

Comments

  • codeofnode
    codeofnode almost 2 years

    I want to implement form based authentication in struts2.

    My directory structure is :

    enter image description here

    My web.xml:

    <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
        <filter>
            <filter-name>struts2</filter-name>
            <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>struts2</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        <security-constraint>
            <display-name>Example Security Constraint</display-name>
            <web-resource-collection>
                <web-resource-name>Protected Area</web-resource-name>
                <url-pattern>/protected/*</url-pattern>
                <http-method>DELETE</http-method>
                <http-method>GET</http-method>
                <http-method>POST</http-method>
                <http-method>PUT</http-method>
            </web-resource-collection>
            <auth-constraint>
                <role-name>manager</role-name>
            </auth-constraint>
            <user-data-constraint>
                <transport-guarantee>NONE</transport-guarantee>
            </user-data-constraint>
        </security-constraint>
    
    
        <!-- Default login configuration uses form-based authentication -->
        <login-config>
            <auth-method>FORM</auth-method>
            <realm-name>Example Form-Based Authentication Area</realm-name>
            <form-login-config>
                <form-login-page>/login.jsp</form-login-page>
                <form-error-page>/error.jsp</form-error-page>
            </form-login-config>
        </login-config>
        <security-role>
            <description> An administrator </description>
            <role-name>
                manager
            </role-name>
        </security-role>
    
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    </web-app>
    

    my login.jsp :

    <form method="POST" action="j_security_check" >
      <table border="0" cellspacing="5">
        <tr>
          <th align="right">Username:</th>
          <td align="left"><input type="text" name="j_username"></td>
        </tr>
        <tr>
          <th align="right">Password:</th>
          <td align="left"><input type="password" name="j_password"></td>
        </tr>
        <tr>
          <td align="right"><input type="submit" value="Log In"></td>
          <td align="left"><input type="reset"></td>
        </tr>
      </table>
    </form>
    

    action in struts :

    <action name= "j_security_check" class="action.LoginAction" >
                <result name="success" >protected/index.jsp</result>
                <result name="error" > error.jsp </result>
                <result name="input" > login.jsp</result>
            </action>
    

    my LoginAction.java

        public class LoginAction extends ActionSupport {
    
            String j_username, j_password;
    
            public String getJ_password() {
                return j_password;
            }
    
            public void setJ_password(String j_password) {
                this.j_password = j_password;
            }
    
            public String getJ_username() {
                return j_username;
            }
    
            public void setJ_username(String j_username) {
                this.j_username = j_username;
            }
    
            @Override
            public String execute() throws Exception {
                if (getJ_username().equals(getJ_password())) {
                    return SUCCESS;
                } else {
                    this.addActionError("Error..!");
                    return ERROR;
                }
            }
    @Override
        public void validate() {
            if ((getJ_username() == null) || (getJ_username().length() == 0)) {
                this.addActionError("Username Empty");
            }
            if ((getJ_password() == null) || (getJ_password().length() == 0)) {
                this.addActionError("Password Empty");
            }
        }
    

    With this i am When i insert same loginid and password, yet i redirected to the error page..

    Can someone give a good link for the same..?

    The example should contain a protected folder, an action class for login..

    thanks..

    • Umesh Awasthi
      Umesh Awasthi over 11 years
      i don't think SO is a place to share code? better come up with what you have done so far and what issue you are facing?
    • codeofnode
      codeofnode over 11 years
      actually m very new to struts and want to learn how to implement form authentication in it.. so i seeking for a start from a perfect example.. on internet there are a few but none is perfect for me. Some lacks with action class and some lacks with a protected folder.. can u help me out plz..
    • Umesh Awasthi
      Umesh Awasthi over 11 years
      i am not sure what you mean by protected folder? and what all you need? can u explain it a more?
    • codeofnode
      codeofnode over 11 years
      the protected folder is any folder which have the protected jsp pages in it simply as resource..
    • codeofnode
      codeofnode over 11 years
      are u there i have just edited with all my coding.. check out.. I am getting the problem that even after submitting same username and password i am getting redirected to error page.. point out my error plz..
    • codeofnode
      codeofnode over 11 years
      Hi HashimR I am using Glassfish server..
    • Umesh Awasthi
      Umesh Awasthi over 11 years
      if you place your JSP in side web-inf even than they will not be accessible to the end user directly
    • HashimR
      HashimR over 11 years
      Where are your username password stored?
    • codeofnode
      codeofnode over 11 years
      @umesh : then what url pattern has to follow, let say i have 20 jsp pages that needs to be protected..
    • codeofnode
      codeofnode over 11 years
      @HashimR I am just checking whether user has given same password and username.. Means if user enters 'jay' as username his password has to be 'jay'.. this is how i am authenticating this form.. u can check out LoginAction.java for clarification..
    • HashimR
      HashimR over 11 years
      It is not how it works. You have to supply a file realm or a jdbc realm from where username and password gets authenticated
    • codeofnode
      codeofnode over 11 years
      I am very new to form authentication in j2ee.. Can u plz tell me what is this realm and how to supply that..?
    • Steven Benitez
      Steven Benitez over 11 years
      @Rambo Place all of your JSPs under WEB-INF and they're all protected. If you are using an MVC framework like Struts2, then you should not be accessing JSPs directly. Instead, the URL will be to the action which will forward to the appropriate JSP.
  • Anupam
    Anupam over 11 years
    I think he is just trying to check the form submission and validation.There is no need for creating a db record etc just for checking your workflow. I am sure he will be adding those things later
  • HashimR
    HashimR over 11 years
    In form based authentication, the action that the form is redirecting to is not a struts action. So he can check the workflow by pointing to his own struts action
  • HashimR
    HashimR over 11 years
    On failure from j_security_check, it will always be forwarded to error page mentioned in web.xml
  • Anupam
    Anupam over 11 years
    Yes, but he mentioned that he is entering the username and password, in that case it should not be forwarded to error page. My point was that your post is not the solution for this problem
  • codeofnode
    codeofnode over 11 years
    @hashimR : Can i do without using realm.. i am not using any database from the action class.. The success is made just with matching of username and password upon entry of form..
  • Anupam
    Anupam over 11 years
    @Rambo Have you tried giving a breakpoint or printing the values in validate() and execute() method. Check if you are getting the right values.Your configuration seems to be correct.
  • HashimR
    HashimR over 11 years
    @anu: You do not need to map the j_security_check to anything. This is managed by the Application Server. However you DO NEED to add usernames. roles and realm information. Each application server has its own way of authenticating this information.
  • HashimR
    HashimR over 11 years
    @Rambo: You do not need to map the j_security_check to anything. This is managed by the Application Server. However you DO NEED to add usernames. roles and realm information. Each application server has its own way of authenticating this information.
  • HashimR
    HashimR over 11 years
    Well thats the point. You don't need to map j_security_check to anything. I have done form based authentication in struts2. :)
  • HashimR
    HashimR over 11 years
    Maybe this will be more helpful.. stackoverflow.com/questions/2362581/…
  • Anupam
    Anupam over 11 years
    +1 oops i got the original question wrong(mixed up with some other concept)