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

JSP Security in Java

Today we are going to learn about JSP-Security in which we learn how we can secure our web application which may be done wither for unfair means or by chance.

JavaServer Pages and servlets make several mechanisms available to Web developers to secure applications. Resources are secured declaratively by verifying them in the application deployment descriptor and assigning a role to them.

Several levels of evidence are available, ranging from basic authentication using identifiers and passwords to sophisticated authentication using certificates.

Role Based Authentication:

The certification mechanism in the servlet specification uses a mechanism called role-based security. This idea is that rather than limiting resources at the user level, we create roles and restrict the resources by role.

We can define different roles in file tomcat-users.xml, which is placed at Tomcat's home directory in conf. An example demonstrates the above:

Listing 1: Defining different roles

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="role1"/>
<role rolename="manager"/>
<role rolename="admin"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="role1" password="tomcat" roles="role1"/>
<user username="both" password="tomcat" roles="tomcat,manager"/>
<user username="admin" password="secret" roles="admin,role1"/>
</tomcat-users>

This file defines a mapping between user name, password, and role. Concern that a given user may have more than one role, for example, user name="both" is in the "tomcat" role and the "role1" role.

Once we identified and defined different roles, a role-based security limitations can be placed on different Web Application resources by using the <security-constraint> element in web.xml file present in WEB-INF directory.

Listing 2: web.xml sample entry

<web-app>
...
 <security-constraint>
 <web-resource-collection>
 <web-resource-name>
 SecuredBookSite
 </web-resource-name>
<url-pattern>/secure</url-pattern>
<http-method>POST</http-method>
<http-method>GET</http-method>
</web-resource-collection>
 <auth-constraint>
<description>
Only admin can  use this app
</description>
 <role-name>admin</role-name>
 </auth-constraint>
</security-constraint>
  <security-role>
<role-name>role1r</role-name>
 </security-role>
 <login-config>
 <auth-method>BASIC</auth-method>
 </login-config>
...
</web-app>

Above entries would mean:

  • Any HTTP GET or POST request to a URL checked by /secured/* would be subject to the security restriction.
  • A person with admin role is given authority to the secured resources.
  • Tthe login-config element is used to explain the BASIC form of certification

Now if we try browsing to any URL including the /security directory, it would show a dialogue box asking for user name and password. If we provide a user "admin" and password "securer" then only we would have access on URL matched by /secured/* because above we have defined user admin with manager role who is allowed to access this resource.

Form Based Authentication:

When we use the FORM authentication method, we must supply a login form to prompt the user for a username and password. Following is a simple code of loginpage.jsp to create a form for the same purpose:

Listing 3: Simple code of loginpage.jsp

<html>
<body bgcolor="#ffffff">
   <form method="POST" action="j_security_check">
      <table border="0">
      <tr>
      <td>Login</td>
      <td><input type="text" name="j_username"></td>
      </tr>
      <tr>
      <td>Password</td>
      <td><input type="password" name="j_password"></td>
      </tr>
      </table>
      <input type="submit" value="Login!">
      </center>
   </form>
</body>
</html>

Here we have to make sure that the login form must contain form elements named j_username and j_password. The action in the <form> tag must be j_security_check. GET must be used as the one of form method.

Same time we would have to modify <login-config> tag to specify auth-method as FORM:

Listing 4: auth-method code

<web-app>
...
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>
               SecuredBookSite
            </web-resource-name>
            <url-pattern>/secured/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint>
            <description>
            Let use this app only by managers
            </description>
            <role-name>manager</role-name>
        </auth-constraint>
    </security-constraint>
    <security-role>
  	   <role-name>manager</role-name>
    </security-role>
    <login-config>
      <auth-method>FORM</auth-method>
      <form-login-config>
        <form-login-page>/loginpage.jsp</form-login-page>
        <form-error-page>/errorpage.jsp</form-error-page>
      </form-login-config>
    </login-config>
...
</web-app>

Now when we try to access any resource with URL /secured/*, it would display above form asking for user id and password. When the container sees the "j_security_check" action, it follows some internal mechanism to verify the caller.

If the login succeeds and the caller is authorized to access the secured resource, then the server uses a session-id to identify a login session for the caller from that point. The server maintains the login session with a cookie containing the session-id. The server returns the cookie back to the client, and as long as the caller exist this cookie with frequent requests, then the server will know who the caller is.

If the login fails, then the server sends back the page identified by the form-error-page setting

Here j_security_check is the action that applications using form based login have to specify for the login form. In the same form we have a text input control called j_username and a password input control called j_password. When we watch this it means that the information contained in the form will be stored to the server, which will verify name and password. How this can be made server specific.

Programmatic Security in a Servlet/JSP:

The HttpServletRequest object provides the below methods, which can be used to get security information at runtime:

Method Description
String getAuthType() The getAuthType() method results a String object that represents the name of the authentication scheme used to protect the Servlet.
boolean isUserInRole(java.lang.String role) The isUserInRole() method returns a boolean value: true if the user is in the given role or false if they are not.
String getProtocol() The getProtocol() method returns a String object representing the protocol that was used to send the request. This value can be determined so that if a secure protocol was used.
boolean isSecure() The isSecure() method returns a boolean value representing if the request was created using HTTPS. A value of 1 means it was and the connection is protected. A value of 0 means the request was not.
Principle getUserPrinciple() The getUserPrinciple() method results a java.security.Principle object that contains the name of the current authenticated user.

Listing 5: Demo of getAuthType Method

import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.security.*;
public class MyServlet extends HttpServlet {
   
    public void init(ServletConfig cfg) throws ServletException 
    {
        super.init(cfg);
    } 

    public void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws IOException, ServletException 
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<HTML>");
        out.println("<HEAD>");
        out.println("<TITLE>");
        out.println("User Authentication");
        out.println("</TITLE>");
        out.println("</HEAD>");
        out.println("<BODY>");
        out.println("<H1>User Authentication</H1>");

        String type = request.getAuthType();
        out.println("Welcome User<BR>");
        out.println("Authentication mechanism: " + type + "<BR>");
        Principal p = request.getUserPrincipal();
        out.println("Wer username is: " + p.getName() + "<BR>");

        out.println("</BODY>");
        out.println("</HTML>");
    } 
}

Output:

Welcome User
Authentication mechanism:Manager
Wer username is:Joe

For example, a JavaServer Page that links to pages for managerswe might have the following snippet:

Listing 6: Snippet

<% if (request.isUserInRole("manager")) { %>
<a href="managers/mgrreport.jsp">Manager Report</a>
<a href="managers/personnel.jsp">Personnel Records</a>
<% } %>

By checking the user's role in a JSP or servlet, we can personalize the Web page to show the user only the items they can use. If we need the user's name as it was entered in the evidence form, we can call getRemoteUser method in the request object.

Conclusion

Java security technology includes a large set of APIs, tools, and fulfillment of commonly used security algorithms, protocols and mechanisms. The Java security APIs spans a wide range of areas, including public key infrastructure, cryptography and authentication, secures communication and use control. Java security technology bestows the programmer with a comprehensive security framework for writing applications, and also bestows the user or administrator with a set of tools to securely manage applications.



Have experience in Oracle, Java and have done certified courses in Android

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