Specifying Security for Basic Authentication using @ServletSecurity

In this section, you will learn about how to specifying security for basic authentication using @ServletSecurity.

Specifying Security for Basic Authentication using @ServletSecurity

Specifying Security for Basic Authentication using @ServletSecurity

In this section, you will learn about how to specifying security for basic authentication using @ServletSecurity.

Types of Security in Java EE

In a multitier enterprise application, several containers are needed to deploy various components of Enterprise tiers. These container also provide security to these components. Two types of security is provided by the container :

  • Declarative security  
    It uses deployment descriptor (web.xml) or annotations , to define security essentials of application's components.

  • Programmatic security
    When declarative security is not enough to hold the application's security model, programmatic security is employed.

Authentication using @ServletSecurity Annotations

@ServletSecurity annotation is used to define security for a Servlet. This annotation offers alternative mechanism which you could achieve through <security-constraint> elements of deployment descriptor or through ServletRegistration interface's setServletSecurity method ()(programmatically).

This method provide us ability to define specific constraints on HTTP functions. Instead of this, you can also define more general constraint that suits to all HTTP methods.

Inside @ServletSecurity annotation, you can implement the following annotations :

  • @HttpMethodConstraint annotation applies to a particular HTTP method.

  • @HttpConstraint annotation applies to all HTTP methods.

The common elements of  @HttpMethodConstraint and @HttpConstraint annotations are given below :

  • transportGuarantee element defines whether or not SSL/TLS is needed(data protection requirements). The connections must satisfy these protection requirements. The legal values for this element is NONE and CONFIDENTIAL.

  • roleAllowed element is employed to define the allowed(authorized ) role names.

SAMPLE CODE

Given below the code in which @ServletSecurity annotation is used for defining authentication :

@WebServlet(name = "UserServlet", urlPatterns = {"/user"})
@ServletSecurity(
@HttpConstraint(transportGuarantee = TransportGuarantee.CONFIDENTIAL,
rolesAllowed = {"TutorialUser"}))

The above annotation specifies that only authorized user will be able to access the  /user URL, who(user) has verified role as TutorialUser. And to protect user name and password data, it will  be transported securely during transit.