In this article, we will look at Java Security in Java EE. We will look at client-side security model for the Java SE environment, including the Web Start and applet deployment modes.We will look at architectural system specification, select appropriate locations for implementation of specified security features, and select suitable technologies for implementation of those features. This is part of a larger series of articles to help you prepare for the java architect exam. The most recent article looked at common java architecture, “Tutorial:Review of Design Patterns for the Java Architect Exam”.

Java Security - What Does It Entail?

Security is often overlooked by architects when they are working on JEE-based systems. This is the case despite the serious damage to the underlying business that can take place if a system is not properly secured. As a JEE architect, you will need to understand the Java security model on both the server and the client. The primary security related objectives for all JEE systems are the following:
  • Confidentiality—to ensure system data and functions are protected from unauthorized access.
  • Integrity—to ensure system data has not been modified or interfered with by a third party for malicious intent or not.
  • Authentication—to ensure the identity of a user or a remote system accessing the system is valid and correct as well as ensuring no impersonation or compromising of the identity.
  • Authorization—to ensure the valid, authenticated user or remote system has the appropriate rights to access system data or execute system functions.
  • Non-Repudiation—to ensure all actions, once performed, cannot be refuted by the user or the system itself.

The use cases one needs to solve will vary by industry setting, the nature of the business as well as the importance attached to each of these characteristics. For example, everyone can access Google and do a search whereas there are a limited number of user who can access a search engine for classified military matters run by a defense company.

Architect’s Knowledge of Security

As an architect, there are a list of topics and resources relating to security that are needed for the java architect’s exam. The key is to for you to have a very good understanding of the foundations on which the Java security model is built as well as how to extend and leverage it for the higher tiers for an architecture within the Java EE environment. The key topics and specifications that you must understand are the following:

There are a number of key use cases to examine the seminal aspects of security in more detail for JEE.

Java Runtime Environment (JRE) Security

Java applications and applets execute in a Java virtual machine (JVM). The JVM provides an environment in which compiled Java programs in the form of Java bytecode can be executed. The benefit of this is that it enables features such as automated exception handling, debugging as well as being bundled with the Java API to form what is known as the Java Runtime Environment JRE). As mentioned previously, all programs that are to run on a JVM myst be compiled into a standard portable binary format into what are known as class file. Generally as a program will consist of a large number of class files, the are packaged together into what is known as a Java archive (jar) file. The .class or jar file is executed by the JVM runtime by emulating the JVM instruction set either through interpreting it or by the use of a just-in-time compiler (JIT). Most systems today tend to use JIT compilers rather than interpreters.

Virtual machines allows for find-grained control over the actions that code is allow by the machine to undertake. One of the fundamental properties of a Java runtime environment is the sandbox. It serves as the basis for all other security layers in the Java programming model. The Java programming language and runtime designers put security very high on the list of things that needed to be well developed when the system was being implemented. In order to achieve this they have provided higher-level security APIs and abstractions in order to provide a firm foundation to build on. The security related APIs and abstractions that have been included in the JRE/Java programming language are the following:
  • automatic memory management
  • strong typing
  • byte code verification
  • secure class loading

In the exam, you will need to focus your efforts on the security APIs and capabilities built on top of these basic capabilities in the Java EE platform. One of the key areas of study is the difference between sandboxed applets and regular Java applications.

Java EE Security with JAAS

Java EE Security is based primarily on JAAS, or the Java Authentication and Authorization Service, which is designed for performing both authentication and authorization at the Java EE tier for both web and EJBs. It serves to separate the authentication system from the Java EE application via a well-defined pluggable API. The JAAS API then knows how to talk to the underlying authentication system like Lightweight Directory Access Protocol (LDAP), Oracle Internet Directory or Microsoft Active Directory. As JAAS being a pluggable API, the vendor only needs to provide a vendor plugin for any Java EE system to make that system available for implementing authentication for an application. The benefit of this is that it makes it easy to swap between authentication systems without the need to alter any of the code for authenticating users. In terms of authorization for both the web and EJB tiers, one has the flexibility of doing authorization either declaratively or programmatically.

One can use JAAS for doing authentication and authorization at both the web and EJB tier of an application. JAAS leverages the fact that applications are web accessible and share authentication systems across tiers to pass authentication context through tiers whenever it is possible. This is done via the implementation of the interface which represents the sharable, validated authentication context.

Overall, JAAS is now the general mechanism provided by the Java Virtual Machine (JVM), for Java code to identify users and roles before allowing or denying access to resources or functionality controlled by the JVM. It is now built into the JVM and is required by the JEE 5 specification, although originally it was a modular install for the JVM. JAAS makes it possible for architects to integrate existing security services into JAAS since all both the authentication and authorization modules are pluggable. Finally the standard JAAS implementation now ships with connectors that implement authentication protocols. One example of this is the Kerberos module. The figure below shows a common Java EE security scenario using JAAS:

Tutorial:Review of Java Security for the Java Architect Exam-c7-jaas-authentication.jpg
Figure:Java EE Security Management Scenarios with JAAS

In the figure above, a user has entered the application through the web tier. The web tier gathers the required authentication information from the user and then authenticates the supplied credentials using JAAS against an underlying security system. If the authentication is successful, a valid user Principal is created, associated with one or more roles and then returned to the user. For each secured web/EJB tier resource, the application server will verify if the principal/role is authorized to access the resource. The Principal is transparently passed from the web tier to the EJB tier as needed.

Although we will not go into depth about neither web tier authentication and authorization nor standalone EJB authentication using JAAS. We will provide a basic outline of web tier security before diving into authorization management in EJB 3. There are two distinct ways for a developer or architect to define how an application should perform security tasks such as user authentication and authorization; They can do this either declaratively or programmatically. Below we will go into detail about both methods.

Declarative Security

Declarative security applies the security requirements for an application’s component’s via deployment descriptors. A deployment descriptor is an XML document with an .xml extension, which describes the deployment settings of an application, a module, or a component. In the declarative security model, the JVM is instructed about the valid users and roles for the system via the deployment descriptor as well as the specific resources and operations that those users and roles can access and execute in the JVM. The declarative method of defining security is very pervasive in the Java EE environment. It is implemented in both the EJB and Servlet containers. The developer or architect defines the security details about security roles, access control, and authentication requirements in the deployment descriptor. These are transformed by the container at run-time into its internal representation or security policy for how to govern the application’s security. The declarative method has a number of advantages over programmatic security:
  • The security configuration is obvious, self-evident, and contained in one place.
  • The security configuration can be modified at deployment time without needing to recompile source code, making the application more configurable.

There is certain structural information that must be provide by deployment descriptors if this information has not been provided in annotations or is not to be defaulted. The formats and schemas will vary depending on the type of components whose behavior or security is being modified. The security elements of deployment descriptors are the following:
  • Enterprise JavaBeans components use an EJB deployment descriptor that must be named META-INF/ejb-jar.xml and contained within the EJB JAR file. This schema for EJB 3.0 deployment descriptors including the security elements is provided in the EJB 3.0 Specification (JSR-220).
  • Web Services components use a jaxrpc-mapping-info deployment descriptor that provides deployment-time mapping functionality between Java and WSDL. This is defined in JSR 109. JAX-WS 2.0 complements this mapping functionality with development-time Java annotations that control mapping between Java and WSDL. This definition is done in conjunction with JSR 181.
  • The schema for web services deployment descriptors is provided in Web Services for Java EE (JSR-109), section 7.1, Web Services Deployment Descriptor XML Schema.
  • Web components as well as security elements use a web application deployment descriptor named web.xml.

Using Annotations

Annotations enable a declarative style of programming, and so encompass both the declarative and programmatic security concepts. Instead of composing a large and often-complex EJB or web deployment descriptor, the programmer can simply use annotations such as to instruct the relevant container directly in the source code. This is different from programmatic security where the programmer calls specific methods in order to decide how to service a business request. With annotations, the programmer is able to define security in a declarative manner. This doesn’t prevent the application assembler from overriding values embedded in the source code of the application at deployment time if so required.

Programmatic Security

When your application has contextual security requirements which cannot be met using declarative security, then you will need to use programmatic security in order to address this problem. Programmatic security is used to define security intents directly within the code of a JEE application rather than externalized to a separate dedicated section of the deployment descriptor. Programmatic security is possible because the JVM can also execute security checks that are not defined in an external deployment descriptor, but defined in the running code itself. Programmatic security provides direct access to the Principal as well as a convenient means to check the Principal’s role in the code. There are two functions that are made available through the EJB context for interrogating the Principal and two methods available for determining the role of either the caller or user. Combined these four methods allow server-side components to service incoming requests while taking into account the identity as well as the role and permissions of the caller. Generally to cover both the general and contextual aspect of application security, most applications use a combination of both declarative and programmatic security checks to provide more comprehensive security than can be done by either approach alone. The key methods for provide programmatic access to security information are the following:
  • isCallerInRole (EJBContext)
  • getCallerPrincipal(EJBContext)
  • isUserInRole(HttpServletRequest)
  • getUserPrincipal(HttpServletRequest)

Authenticating Subjects

In a secure JEE application, authentication is the process of verifying that a user is who they claim. When a client logs on to the JEE system, it is associated with a security identity during the session. Once the system has authenticated the user, it establishes the identity for the user. For example, when a bank asks a client for a valid form of identification, it will then compare it with the picture of individual in order to authenticate the client’s identity. Similarly, if a user logs in to their bank’s online banking application, they are required to provide a username and password in order to authenticate themselves. The user’s credentials are used by the online banking system to determine whether the user is who they claim to be. If so the online banking system will allow them to see their account balances, transfer money, and pay bills.

Principals: Multiple Identities

In JAAS, a user can have multiple identities. These identities are not directly associated with a Subject but instead each Subject contains any number of Principals which is the identity in JAAS. Therefore a Subject is a container for all of Subject’s identities in a manner similar to how a wallet or purse contains all of your id cards (i.e. driver’s license, social security, insurance card, store loyalty card).

Therefore, one a user authenticates with a JAAS-enable system, each of these identity Principals is associated to his Subject. By breaking down a Subject’s identities into Principals creates clear delineation of responsibility between the two:
  • Principals are used to communicate to JAAS the identity of a user
  • Subjects aggregate the user’s multiple identities.

Also, this scheme permits easier integration with non-JAAS authentication systems such as single-sign-on services. For example, when using a single-sign-on service, after a Subject is authenticated, all of the different users are converted to Principals and bundled into the Subject. This scheme allows the Subject to serve as an umbrella for all the different identities the user can take on via the Subject.

Subjects, Principals and Roles

The Subject can not only contain numerous Principals representing different identities but also can represent numerous roles the Subject is authorized to perform. For example, a user, Joe Q Public could be allowed to perform the following of roles:
  • Administer all users, including the approval of new user requests, deleting users, or resetting their passwords.
  • Define system-wide configuration properties such as for mail server, directory server, etc for the company.

The Principal would encapsulate each of these roles in JAAS. One could in JAAS, create two roles for the above items (i.e. User Administrator and System Administrator) and then associate them with the Principals rather than directly with a Subject. John Q Public’s Subject, would contain Principals that represent both of these Administration roles. This is shown in the figure below:

Tutorial:Review of Java Security for the Java Architect Exam-c7-mappinguserstoroles.jpg
Figure:Mapping of Employee and Manager Roles to Permissions

The primary benefit of separating roles into their own Principals is the ease in which one can manage and maintain the user’s permissions as the role-based Principal can be easily associate with a number of users who have responsibility for the system in a particular area.

What is a Credential?

We also have the concept of Credentials in addition to those related to Principals and Subjects. The most common types of credential are a username and password pair. Credentials can vary significantly from one system to another depending on the authentication protocol or system used. They could be either one or a combination of the following:
  • A single credential, like your password for a voice mail system.
  • A physical credential, like a garage door opener to open your garage.
  • A digital certificate.
  • A mix of physical and keyed-in credentials, like your ATM card and your PIN number. Biometric credentials, like your thumbprint or retinal scan.

So basically, anything that can be used to prove your identity is a credential. In JAAS, there are two types of credentials held by a Subject:
  • public credentials an example would be anything that can be obviously seen such as your username.
  • private credentials an example would be something that is hidden such as your password.

Since any Object can be defined as a credential, JAAS doesn’t specify an interface, or type. Therefore it is left up to the code that uses the credential to determine exactly what the particular credential means.

Access Control - Checking for Permissions

After a Subject has been authenticated and has a set of Principals associated with it, JAAS can begin to enforce access control. Access control is the process of verifying that the Subject has been granted any rights required to access a particular resource. The resource could be code or it could be a JSP page in an application. JAAS implements access control by wrapping Permission checks around blocks of code or by using pattern matching to secure a resource via a container-specific abstraction called a realm. As for the block of code, it can be an entire method or a single line of code. In fact, wrapping the smallest piece of code is considered the best option for performance and fine grained security control.

Access control is generally done in JAAS using “try/catch” algorithm. This means that it tries to execute certain code, and if unsuccessful handles all security exceptions that are thrown due to permission failure for the Subject. Another means of doing permission checking is to first check if the Subject has the appropriate permissions before trying to execute a piece of code.

Before any code can execute, JAAS must verify that the Subject has the appropriate Permissions to execute the code. If the Subject doesn’t has the appropriate Permissions, a security exception is thrown. Once JAAS has authenticated the Subject and the related Permissions are loaded, JAAS-enabled code will execute with the actual code being protected by Permissions often does the checking itself.

So you may ask how does the JAAS model of access control require code that is performing the sensitive action to do the permission checking? If access control was wrapped around say’s delete() method, then the method itself would do the security check. This is the most efficient approach since trying to find all the places that call can delete() is much more time consuming than putting access checks in the method itself. A code-centric approach means that the code must include Permission checks, and be knowable of which Permissions to check.

There maybe situations where using such a model of access control may be cumbersome to maintain. You could have a situation where new types of Permission are being added that impacts on deleting a file using the’s delete() method. You would then need to modify the delete() method to check for this Permission.The way around this is to realize that this is what is known as a cross-cutting concern (i.e. an aspect relevant across all tiers of the application). In this case, you can use one of a number of strategies such as Dynamic Proxies, declarative meta-information via XDoclet or Annotations in J2SE 1.5 or Aspect Oriented Programming, in order to provide a cleaner more easily maintainable method for maintain access control code across an application.

What are the Security Threats?

The security aspects of all applications, including Java EE applications, tend to undergo higher scrutiny today as the potential for damage to the corporation is too high if their corporate data is compromised in any way. The Java EE platform provides robust support for many of the scenarios which need to be address in order to deal with the many security aspects of an application. Java EE applications can do the following:
  • Provide fine grain access control to application data as necessary
  • Provide fine grain access control access to application business logic as necessary
  • Provide secure messaging through the encryption and decryption of all data as necessary
  • Interoperate with existing enterprise resource systems (ERSs) for access control to data and business logic held within these ERSs as necessary

These capabilities have been designed within the JEE platform since its inception. Since then it has further been enhanced in order to address the requirements of applications for a strong and comprehensive security model end to end. The most important features of the Java EE platform will be discussed below.

Client-Side Security

On the client side, there are a number of possible channels that need to be considered. This includes applets running in a web browser via the Java plug-in as well as applications deployed via Java Web Start or installed directly on the machine. In both cases, the end user is allowed to control what client-side resources the code can and cannot accessed or modified. All applets or applications compiled into Java bytecode must be signed before they can request access to client-side resources. Otherwise any code that attempts to access client-side resources, such as the local file system, or to open a socket to another server will prompt the end user with a request in a modal dialog asking whether to permit or deny the operation.

This only differs when Java applications are installed directly onto a client machine. In this case they do not run inside a sandbox so there is no access controls on any operation that is executed. Regardless of the deployment of an application, once installed, the architect’s responsibility is to ensure that sensitive data transited between the server and the client is encrypted and impenetrable to malicious entities. The most straightforward means of achieving this is to encrypt all data using Secure Sockets Layer (SSL). Java supports SSL for use in encrypting both RMI traffic (RMI over SSL) and HTTP traffic (HTTP over SSL, or HTTPS).

Server-Side Security

There are actually a number of aspects to Java Security on the server-side. There is security for accessing EJB and web containers, JMS servers as well as for accessing Enterprise Information Stores (EISs).

EJB Container Security

The security for the EJB container is fortunately focused primarily around the authorization model. For authentication, as we have mentioned previously, this task is normally done by a JAAS login model which then passes the authentication information to the EJB container via an authenticated Principal. Authentication can be either declaratively or programmatically. Similarly for the authorization model, it also centers on checking whether the authenticated Principal is allowed to access an EJB resource based on the Principal’s role. There are two methods provided on the EJBContext interface to allow developers to check programmatically a user’s permission before a method is invoked containing potentially sensitive business logic. The two methods are the following:
  • isCallerInRole
  • getCallerPrincipal

The declarative approach for applying access controls to these methods involves specifying at design time what users and roles can access specific EJB methods. One can access by role methods that are part of the method-permission element. You can also define a “run as” capability for a method that allows for the substitution of the original identity of the caller for an identity that has been defined declaratively.

Web Container Security

For Servlets and JSPs running in the web container, they also have access to security information at runtime to decide whether to allow or deny access to incoming requests similarly to EJB running in an EJB container. There are two methods that are part of the HttpServletRequest interface for doing this. They are:
  • isUserInRole
  • getUserPrincipal

Security-wise, the web container typically has to do alot more work than an EJB container since it is the public facing part of the application. The premise for the design of many Java EE applications is that the web layer does the majority of the authentication and authorization for the system. But in fact most requests made through the web layer, are allowed unquestioned access to all resources of the system. This creates an obvious security hole. The key mechanism for controlling access to system functionality is URL authorization, where the URLs of the application are defined to have a specific security meaning that can be ascertained using regular expressions. For example, at design time, one uses the deployment descriptor (i.e. web.xml) to capture rules such as “all URLs of the form /admin/* should only be accessible to users that have been assigned the Administrator role.” in order to enforce these access rules at runtime on the web server. The sequence of events occurring when a user attempts to access a secured resource via a URL, is the following:
  • When a user initially attempts to access a secured resource, the user is redirected to a login page by the web server, which detects that the user has not been authenticated or authorized.
  • The user fills in authentication information in a form that collects the required information. In most cases, this will be a username and password, but this can vary depending on the level of security required.
  • The form is posted back to the web server where the user is authenticated by the web server.
  • The web server sets credentials of the user for the duration of the session as to their access rights for the system.

The figure below outlines the sequence of events:

Tutorial:Review of Java Security for the Java Architect Exam-c7-securityeventsequence.jpg
Figure:Security Event Sequence for JEE Application

In the figure above, it is clear that the web container and the EJB container maintain separate security contexts. Each of the contexts are derived at runtime from the information provided either via annotations or deployment descriptors. When a web resource such as a JSP page tries to invoke an EJB resource in order to complete a business process, the EJB container leverages the security context/credential associated with the JSP call to determine whether to authorize (or reject) the request. If the request is authorized, the web container transfers control of the request to the EJB container. When the request is processed and the response is returned by the EJB, the EJB container will return the result to the web container for further processing. When it has completed its processing the result is returned to the client where it is rendered in the web browser.

Web Service Security

A Web services security standards framework was proposed in April 2002 by Microsoft and IBM in the white paper “Security in a Web Services World: A Proposed Architecture and Roadmap”. Soon vendors had put together a Web Services Security (WSS) framework. This framework encompassed different specifications, each of them addressing specific aspects of security. This is shown in the figure below:

Tutorial:Review of Java Security for the Java Architect Exam-c7-webservicesecuritystandardsframework.jpg
Figure:Web Service Security Standards Framework

Within this framework, WS-Security provides a message security model as well as the specification for mechanisms to attach signature and encryption headers to SOAP messages. WS-Policy serves to describe security policies, such as required security tokens and supported encryption algorithms. This includes more general policies adopted by a Web service; and the mechanisms from which trusted SOAP message exchanges can be built. WS-Trust defines the model for establishing direct and brokered trust relationships, including third parties and intermediaries, via the creation of security token issuance services. WS-Privacy defines a model for embedding a privacy language into WS-Policy and for associating privacy claims with a message in WS-Security.

On top of such standards, further specifications were introduced. This includes WS-SecureConversation with the objective of extending the single message security provided by WS-Security to a conversation consisting of multiple message exchanges; WS-Federation which has the goal of describing how to manage and broker trust relationships in a heterogeneous federated environment; and finally WS-Authorization, which provides support for the specification of authorization policies and for managing authorization data.

In terms of the JEE 5 platform, support for web services security is not as complete as one would like. This is because message-level encryption is not required to be supported in the standard implementation despite there being multiple mechanisms existing for supporting message level encryption. There are two initiatives that have been completed to address these issues. They are:

The Definition of Security Behavior

JAAS is the means by which Java EE application servers are instructed to enforce a desired security policy for a JEE application. As the JAAS API is a pluggable API, is based primarily on the Java Authentication and Authorization Service (JAAS) API. the Java EE application will only be required to talk to the JAAS API, while the JAAS API will communicated with the underlying authentication systems like Lightweight Directory Access Protocol (LDAP), such as Microsoft Active Directory or Oracle Internet Directory (OID) using a vendor plug-in. Therefore outside of authentication, the application server internally uses JAAS to perform authorization for both the web and EJB tiers both declaratively and programmatically. The key to all aspects of security using JAAS is the interface which will hold the roles and associated access rights to various part of the system.

Commonly Encountered Security Threats

There are a number of commonly encountered security threats, and we will look at some of the “design patterns” for how these types of security threats are typically addressed in JEE applications. As it is impossible to cover exhaustively every security threat as well as the fact that the nature of these threats will evolve over time, therefore the architect is encourage to update their knowledge on security threats on a regular basis through online research. As for now, the list below outlines some of the most common security threats:
  • Man in the middle attacks—this type of attack involves a malicious party intercepting messages sent between the client and server as part of a valid conversation or transaction, either for the purpose of gaining access to unauthorized information or to achieving an outcome favorable to the malicious party. The means to address this is to encrypt all network traffic using strong SSL guards effectively against this attack.
  • Session hijacking (replaying data)—this type of attack is related to man in the middle where the malicious party inspects the system and identifies how the server recognizes connected clients. The malicious party can then steal the identity of a real client and use it to interact with the server in order to either to gain unauthorized access to data or to achieve an outcome desirable to the malicious party and undesirable to the trusted party. The way to address this is through strong data encryption and for architects to ensure that no sensitive information is used in the application URL that would facilitate a hacker who is trying to hijack a session.
  • Password cracking—this type of attack uses brute force to repeatedly attempt to login as a valid user by guessing their password. The approach to counter this attack is by using business logic that dictates minimum complexity rules on passwords selected by users as well as shutting the user out of the system after a specified number of unsuccessful login attempts.
  • Phishing—this type of attack is where users are misdirected to a false or hoax version of the system and then tricked into releasing sensitive information. The valid information that is captured at the false site is then used by the malicious party to gain access to the real system. There are two sides to the solution for phishing. On part is about educating users of potentially fake sites and the other side is about engineering such as monitoring for unusual system activity on the part of users.
  • Social hacking—this type of attack involves social engineering where members of the opposite sex are used to gain unauthorized access to the system. At present, there is no Java API or library existed for countering this type of attack vector.
  • Network sniffing—this type of type is one of the simplest and oldest attacks; it involves reading unencrypted data from the network via a sniffing tool. Typically, man in the middle, session hijack attacks, and so on are built on top of a sniffing attack. The solution for this type of attack is strong data encryption.

There is one other type of attack that is attempted on web applications that use JavaScript or XSS (cross-site scripting, Type 0, 1, and 2). With the advent of rich internet applications (RIAs), these types of applications that are built on top of JavaScript and XSS bring security risks that a JEE architect must be aware of and resolve.

Defining a Security Model

As the scope of security is wide-ranging and the implications very serious if any compromise occurs, the Java EE architect is well advised to create and maintain a security model, consisting of a roadmap or blueprint, that details how the Java EE application enforces security, across all of the topics and threats listed above. The model doesn’t in and of itself guarantee a secure application, but it does serve to ensure that the architect has considered the potential threats that could be faced and employed the appropriate measures to mitigate or counteract these threats. Basically, the model should cover the following aspects:
the system infrastructure including hardware, the networking layer and any additional components
  • User authentication
  • User authorization
  • Auditing
  • Data encryption
  • System hardening against the commonly encountered attacks listed in the previous section


Security is across cutting concern that affects all layers of a JEE application from the client to the persistence tier. It is important the your JEE application’s approach to security is robust. The basic underlying Java platform provides the basic capabilities to eliminate memory buffer attacks and similar sorts of threat. JEE builds on top of the capability via JAAS which provides the JEE architect with the tools to both programmatically and declaratively define authentication and authorization for the system. In addition there are other matters that an architect needs to consider when using web services such as message level encryption, and many of the other WS-* security tools. With your knowledge of these tools, you should be ready to deal with all matters of Java Security for the Java Architect Exam.