Nearby lessons

34 of 34

Servlet - Examples: Security

📌 What You Will Learn
  • See complete runnable servlet programs
  • Understand the output of each program
  • Copy and deploy programs in Tomcat

Declarative and programmatic security examples including Basic Authentication.

Declarative Security(web.xml declarations)

It defines the resources which have to be protected, which roles are allowed to access and security

constraint is applicable for which type of http methods etc...

Example01
JCode Cell
1 
2 <security-constraint>:
3

Declarative Security(web.xml declarations)

It defines the type of authentication what we are using.

3.<security-role>

It defines the security roles which are allowed in the web application.

Note:

The above 3 tags are direct child tags of <web-app> and hence we can place anywhere within the

<web-app>

Example02
JCode Cell
1 
2 <login-config>:
3

Declarative Security(web.xml declarations)

This tag defines the following 3 child tags

Example03
JCode Cell
1 
2 <security-constraint>:
3

Declarative Security(web.xml declarations)

Defines the resource which has to be protected

Example04
JCode Cell
1 
2 <web-resource-collection>
3

Declarative Security(web.xml declarations)

Authorization constraint which determines what roles are allowed to access the resource.

Example05
JCode Cell
1 
2 <auth-constraint>
3

Declarative Security(web.xml declarations)

It specifies what type of protection is required when trasporting the resource accross the

network.

1.<web-resource-collection>:

This tag contains the following 4 child tags

1.<web-resource-name>

2.<description>

3.<url-pattern>

4.<http-method>

It specifies the Http method to which security constraint is applicable.

If we are not using this tag, then security constraint is applicable for all methods.

2.<auth-constraint>:

It specifies which security roles are allowed to access protected resource.

It contains the following 2 child tags.

1.<description>

2.<role-name>

If the security constraint is applicable for all the roles, we have to specify as follows...

<role-name>*</role-name>

3.<user-data-constraint>:

This tag contains the following 2 child tags

1.<description>

2.<transport-guarentee>

This tag specifies what type of guarantee we are providing while transporting the resource

across the network.

The allowed values for this tag are:

1.NONE:

It means the data is transported in plain text form.

It is the default value

2.INTEGRAL:

It means the data should not be changed in trans

  • CONFIDENTIAL:

It means the data is transported in encryption form.

The required priority order is: CONFIDENTIAL,INTEGRAL and NONE.

Example06
JCode Cell
1 
2 <user-data-constraint>
3

Declarative Security(web.xml declarations)

This tag specifies the type of authentication we are using.

It contains the following child tags

1.<auth-method>

It specifies the authentication method

The allowed values are

BASIC

DIGEST

FORM

CLIENT-CERT

Example07
JCode Cell
1 
2 <login-config>
3

Declarative Security(web.xml declarations)

It specifies the location where we are storing authentication information.

It is required only for basic authentication.

Example08
JCode Cell
1 
2 <realm-name>
3

Declarative Security(web.xml declarations)

This tag is required to specify login page url and error page url in the case of Form based

authentication.

This tag contains the following 2 child tags

1.<form-login-page> /login.html </form-login-page>

2.<form-error-page> /error.html </form-error-page>

3.<security-role>:

It can be used to define security roles in the web application.

This tag contains the following 2 child tags.

1.<description>

2.<role-name>

Summary of all security related tags:

Example09
JCode Cell
1 
2 <form-login-config>
3

Declarative Security(web.xml declarations)

Example10
JCode Cell
1 
2 <web-app>
3 <security-constraint>
4 <web-resource-collection>
5 <web-resource-name>
6 <description>
7 <url-pattern>
8 <http-method>
9 </web-resource-collection>
10
11 <auth-constraint>
12 <description>
13 <role-name>
14 </auth-constraint>
15
16 <user-data-constraint>
17 <description>
18 <transport-guarentee>
19 </user-data-constraint>
20 </security-constraint>
21
22 <login-config>
23 <auth-method>
24 <realm-name>
25 <form-login-config>
26 <form-login-page>
27 <form-error-page>
28 </form-login-config>
29 </login-config>
30
31 <security-role>
32 <description>
33 <role-name>
34 </security-role>
35
36 </web-app>
37

Demo Program for Basic Authentication

<tomcat-users>

...

<role rolename="durgarole"/>

<user name="durga" password="java" roles="durgarole" />

<user name="ravi" password="scjp" roles="durgarole" />

</tomcat-users>

postreqform.html:

Example11
JCode Cell
1 
2 <web-app>
3 <servlet>
4 <servlet-name>FirstSevlet</servlet-name>
5 <servlet-class>FirstServlet</servlet-class>
6 </servlet>
7
8 <servlet-mapping>
9 <servlet-name>FirstSevlet</servlet-name>
10 <url-pattern>/test</url-pattern>
11 </servlet-mapping>
12
13 <security-constraint>
14 <web-resource-collection>
15 <web-resource-name>CheckedServlet</web-resource-name>
16 <url-pattern>/test</url-pattern>
17 <http-method>POST</http-method>
18 <http-method>GET</http-method>
19 </web-resource-collection>
20
21 <auth-constraint>
22 <role-name>durgarole</role-name>
23 </auth-constraint>
24
25 </security-constraint>
26
27 <login-config>
28 <auth-method>BASIC</auth-method>
29 </login-config>
30
31
32 <security-role>
33 <role-name>durgarole</role-name>
34 </security-role>
35
36 </web-app>tomcat-users.xml:
37

Demo Program for Basic Authentication

Example12
JCode Cell
1 
2 <html>
3 <body><h1> Basic Authentication Demo to send POST request</h1>
4 <form action = "/webs1/test" method="POST">
5 Enter Text :<input type=text name="text">
6 <input type=submit>
7 </form>
8 </body>
9 </html>
10

FirstServlet.java

Demo Program for FORM-BASED Authentication:

login.html:

Example13
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 public class FirstServlet extends HttpServlet
6 {
7 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
8 {
9 PrintWriter out = resp.getWriter();
10 out.println("<h1>Get:After Authentication only we can access this servlet</h1>");
11 }
12 public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
13 {
14 PrintWriter out = resp.getWriter();
15 out.println("<h1>POST:After Authentication only we can access this servlet</h1>");
16 }
17 }
18
Output

    <h1>Get:After Authentication only we can access this servlet</h1>
    <h1>POST:After Authentication only we can access this servlet</h1>
          

FirstServlet.java

<h1>Your credentials are not correct. Please provide valid credentials</h1>

web.xml:

Example14
JCode Cell
1 
2 <html>
3 <body><h1> Welcome to Durga Software Solutions</h1><br>
4 <h2>Please login to avail the facilities....</h2>
5 <form action = "j_security_check">
6 Enter Name :<input type=text name="j_username"><br>
7 Enter password :<input type=password name="j_password"><br>
8 <input type=submit>
9 </form>
10 </body>
11 </html>error.html:
12

FirstServlet.java

Example15
JCode Cell
1 
2 <web-app>
3 <servlet>
4 <servlet-name>FirstSevlet</servlet-name>
5 <servlet-class>FirstSevlet</servlet-class>
6 </servlet>
7
8 <servlet-mapping>
9 <servlet-name>FirstSevlet</servlet-name>
10 <url-pattern>/test</url-pattern>
11 </servlet-mapping>
12
13 <security-constraint>
14 <web-resource-collection>
15 <web-resource-name>CheckedServlet</web-resource-name>
16 <url-pattern>/test</url-pattern>
17 <http-method>GET</http-method>
18 <http-method>POST</http-method>
19 </web-resource-collection>
20 <auth-constraint>
21 <role-name>durgarole</role-name>
22 </auth-constraint>
23 </security-constraint>
24
25 <login-config>
26 <auth-method>FORM</auth-method>
27 <form-login-config>
28 <form-login-page>/login.html</form-login-page>
29 <form-error-page>/error.html</form-error-page>
30 </form-login-config>
31 </login-config>
32
33 <security-role>
34 <role-name>durgarole</role-name>
35 </security-role>
36 </web-app>tomcat-users.xml:
37 <tomcat-users>
38 ...
39 <role rolename="durgarole"/>
40 <user name="durga" password="java" roles="durgarole" />
41 <user name="ravi" password="scjp" roles="durgarole" />
42 </tomcat-users>postreqform.html:
43 <html>
44 <body><h1> Basic Authentication Demo to send POST request</h1>
45 <form action = "/webs2/test" method="POST">
46 Enter Text :<input type=text name="text">
47 <input type=submit>
48 </form>
49 </body>
50 </html>
51

FirstServlet.java

Example16
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 public class FirstServlet extends HttpServlet
6 {
7 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
8 {
9 PrintWriter out = resp.getWriter();
10 out.println("<h1>Get:After Authentication only we can access this servlet</h1>");
11 }
12 public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
13 {
14 PrintWriter out = resp.getWriter();
15 out.println("<h1>POST:After Authentication only we can access this servlet</h1>");
16 }
17 }
18
Output

    <h1>Get:After Authentication only we can access this servlet</h1>
    <h1>POST:After Authentication only we can access this servlet</h1>
          

Programmatic Security

If the authenticated user belongs to the specified role then this method returns "true"

If the authenticated user not belongs to the specified role or if the user not authenticated then

this method returns false.

Example17
JCode Cell
1 
2 public boolean isUserInRole(String rolename)
3

Programmatic Security

Returns the authenticated user name(login name)

If the user has not been authenticated then this method returns null.

Example18
JCode Cell
1 
2 public String getRemoteUser()
3

Programmatic Security

Returns java.security.Principal object which contains user name.

Returns null if the user has not been authenticated.

Eg:

Example19
JCode Cell
1 
2 public Principal getUserPrincipal()
3

Programmatic Security

The main problem in this approach is we are hard coding the role names in the servlet.

If there is any change in the role-name, modifying servlet code is costly and creates maintanence

problems.

To overcome this problem we have to use <security-role-ref> tag. By using this tag we can map

hard coded role names with original role name.

Example20
JCode Cell
1 
2 if(req.isUserInRole("admin"))
3 {
4 out.println("Admin related response");
5 }
6 else
7 {
8 out.println("non admin related response");
9 }
10
Output

    Admin related response
          

Programmatic Security

where admin is logical role name and durgaadmin is original role name.

Example21
JCode Cell
1 
2 <servlet>
3 .....
4 <security-role-ref>
5 <role-name>admin</role-name>
6 <role-link>durgaadmin</role-link>
7 </security-role-ref>
8 </servlet>
9

Demo Program for programmatic Security

Example22
JCode Cell
1 
2 <web-app>
3 <servlet>
4 <servlet-name>FirstSevlet</servlet-name>
5 <servlet-class>FirstSevlet</servlet-class>
6 <security-role-ref>
7 <role-name>hero</role-name>
8 <role-link>durgaadmin</role-link>
9 </security-role-ref>
10 </servlet>
11
12 <servlet-mapping>
13 <servlet-name>FirstSevlet</servlet-name>
14 <url-pattern>/test</url-pattern>
15 </servlet-mapping>
16
17 <security-constraint>
18 <web-resource-collection>
19 <web-resource-name>CheckedServlet</web-resource-name>
20 <url-pattern>/test</url-pattern>
21 <http-method>GET</http-method>
22 </web-resource-collection>
23 <auth-constraint>
24 <role-name>durgaadmin</role-name>
25 <role-name>durgamanager</role-name>
26 </auth-constraint>
27 </security-constraint>
28
29 <login-config>
30 <auth-method>BASIC</auth-method>
31 </login-config>
32
33 <security-role>
34 <role-name>durgaadmin</role-name>
35 </security-role>
36
37 <security-role>
38 <role-name>durgamanager</role-name>
39 </security-role>
40 </web-app>tomcat-users.xml:
41 <tomcat-users>
42 ...
43 <role rolename="durgaadmin"/>
44 <role rolename="durgamanager"/>
45 <user name="pawan" password="kalyan" roles="durgaadmin" />
46 <user name="shiva" password="scwcd" roles="durgaadmin" />
47 <user name="mahesh" password="babu" roles="durgamanager" />
48 </tomcat-users>login.html:
49 <html>
50 <body><h1> Programatic Security To send Post Request</h1>
51 <form action = "/webs3/test" method="POST">
52 Enter Text :<input type=text name=uname>
53 <input type=submit>
54 </form>
55 </body>
56 </html>
57

FirstServlet.java

OCWCD

Question Bank

Example23
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 public class FirstSevlet extends HttpServlet
6 {
7 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
8 {
9 PrintWriter out = resp.getWriter();
10 String name = req.getRemoteUser();
11 out.println("<h1>Hi .."+name+"</h1><br>");
12 if(req.isUserInRole("hero"))
13 {
14 out.println("<h1>This is Hero Home Page</h1>");
15 }
16 else
17 {
18 out.println("<h1>This is Others Home Page</h1>");
19 }
20 }
21 public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
22 {
23 doGet(req,resp);
24 }
25 }
26
📝 Key Takeaways
  • Every example is complete and compiles as-is
  • Examples are grouped by topic
  • Typing programs is the fastest way to learn servlets