Beruflich Dokumente
Kultur Dokumente
com
Java EE Security
n
Web Module Security
n
EJB Module Security
n
Application Client Security
n
Securing Java EE Web Services
n
Hot Tips and more...
By Masoud Kalali
each one of them has its
SECURITY IN JAVA EE APPLICATIONS separate authorization
mechanism suitable for its
Java EE security supports a fine set of security functionalities in deployed components.
the specification level. These capabilities include authentication,
Each Java EE application can
authorization, data integrity and transport security. Before going deep
consist of multiple modules
into the Java EE security, everyone should know the following terms:
as shown in Figure 2. Each
A User is an individual identity which is defined in the identity storage. one of these modules
The storage which can be an RDBMS, flat file or LDAP server contains can have zero or more
user attributes like username and password. deployment descriptors
A Group is a set of users classified with a set of common characteristics which can contain different
which usually lead to a set of common permissions and access levels. types of configuration for
the application components
A Security Realm is the access channel for the application server to
(JSPs, Servlets, EJBs, Etc.)
storage containing users authentication and grouping information.
including but not limited to
www.dzone.com
A Role is a Java EE concept to define access levels. A Java EE their security descriptions.
application developer specifies which roles can access which set of the Figure 3 shows these files
application functionalities. These roles are then mapped to users and and their locations.
Figure 3: Java EE application modules and their
groups using the vendor specific configuration files. Although all of the vendor deployment descriptors
manager role to access a resource with a URL matching /mgr/* in our The simplest content for the login.jsp is as follow:
Web application.
<form action=j_security_check method=POST>
<input type=hidden name=A value=1>
Listing 1: Declaring security constraint in web.xml
<input type=hidden name=B value=2>
</form>
<security-constraint>
<display-name>mgr resources</display-name>
<web-resource-collection>
<web-resource-name>managers</web-resource-name> The login-error.jsp page can contain any sort of information
<description/>
<url-pattern>/mgr/*</url-pattern> you feel necessary for the users to understand they provided wrong
<http-method>GET</http-method>
<http-method>PUT</http-method> credentials and they can probably recover the password and so on.
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint> Now it is time to let the application server know where the users
<description/>
<role-name>manager</role-name> credentials are stored so it can authenticate the received credentials
</auth-constraint>
</security-constraint> with them and decide whether the user is authentic or not. This is
<security-role>
<description>All Manager </description> where vendor specific deployment descriptor comes into play. Basically
<role-name>manager</role-name>
</security-role>
we need to map the roles we used in the standard deployment
descriptor to users and groups (in some cases users and roles) defined
We defined a security constraint, defined a collection of resources in security realm. Different vendors use different configuration elements
matching the /mgr/* URL and defined a constraint over the GET, PUT, to map roles to individual users and groups of users in the security
and POST methods. Then we permitted the manager role to access the realm. The following table shows how a role can be mapped to users
constrained resources. The URL pattern can specify anything from a and groups in different application servers.
Servlet to a set of JSP files. We can include as many roles as we need in
the auth-constraint element. Application Server Mapping Sample
GlassFish: <security-role-mapping>
Any security role referenced in the auth-constraint elements should sun-web.xml <role-name>manager</role-name>
<principal-name>JoneDoe</principal-name>
be defined using a security-role element as we did for the manager role. <group-name>managers</group-name>
</security-role-mapping>
So far we told which role has access to the secured resource but we still
Geronimo: <security-realm-name>file-realm</security-realm-name>
need to let the application server know how to authenticate the users geronimo-web.xml
<security>
and later on how to determine which roles the user has. <role-mapping>
<role role-name=manager>
Java EE containers provide some standard authentication mechanisms <principal class=org.apache.geronimo.security.realm.
providers.GeronimoUserPrincipal name=JohnDoe />
for using in the Web modules. These methods with their specification <principal class=org.apache.geronimo.security.realm.
providers.GeronimoGroupPrincipal name=managers />
names are as follow: </role>
</role-mapping>
</security>
(1) HTTP Basic Authentication: BASIC
(2) Digest Authentication: DIGEST The realm need to be created as a top level realm in the application
server management console or it can be added to the web application
(3) HTTPS Client Authentication: CLIENT-CERT as a deployment module. Using the second way, the security realm will
(4) Form-Based Authentication: FORM be deployed along with the application and will be underployed when
we undeploy the application.
In the first two methods container initiates an HTTP basic authentication JBoss: The JBoss case is different because JBoss uses the concept of Security
jboss-web.xml Domain which is defined in a separate descriptor file named jboss-web.
and usually the Web client (Browser) shows the standard dialog to xml and is located in the conf directory of server instance. Following
collect the user name and the password. The only difference is that when element is used to specify the security domain.
using DIGEST, client sends a digest of the password instead of sending <security-domain>java:/jaas/jboss-sec-domain</security-domain>
it in clear text. To use any of these methods we only need to include the For JBoss application server some of the declaration we specified
following snippet in the web.xml. in *-web.xml is moved to login-config.xml which includes both role
mappings and security realm definition. A security domain can be
deployed with the enterprise application itself or it can be defined in
<login-config>
the global login-conf.xml file. A sample security domain definition is
<auth-method>BASIC</auth-method>
<realm-name>file-realm</realm-name> shown in the listing 2.
</login-config>
Table 1: Application server specific role mappings
security-role-ref We can alias a role with a more meaningful title and then link the alias to
Passwords and user names are not protected from eavesdropping real realm using this element. For example:
when we use FORM or BASIC authentication methods. To protect them <security-role-ref>
<role-name>mid_level_managers</role-name>
from being viewed and intercepted by third parties we should enforce <role-link>manager</role-link>
transport security. </security-role-ref>
tag containing the resource which need transport protection. For @DeclareRoles Prior to referencing any role, it should be defined. The @DeclareRoles
acts like security-role element in defining the roles used in application.
example we can add the following snippet inside the security-constraint
of Listing 1 to enforce use of SSL when user is accessing manager @RunAs Specifies the run-as role for the given Components.
with SSL enabled) to communicate with client. Different application Table 3: Security Annotations in Java EE 6
servers use a variety of methods to define and configure the HTTPS Each of the annotations included in table 3 can be placed on different
listeners. Each listener will have a dedicated port like 8080 for HTTP targets like methods, classes or both and on different Java EE
and 8181 for HTTPs. components like Servlets and EJBs. Table 4 shows what kind of targets
are supported for each one of these annotations.
In production environment we usually front the application server
with a Web server or a dedicated hardware appliance to accelerate Annotation Targets Level Target Kind
the SSL access among other tasks like hosting static content, load @DeclareRoles Class EJB, Servlet
distribution, decorating HTP headers and so on.
@RunAs Class EJB, Servlet
For the security purpose the front end Web server or appliance (like a
@ServletSecurity Class Servlet
Cisco PIX 535, F5 Big IP, etc) can be used to accelerate SSL certificate
processing, unify the access port to both HTTP and HTTPS, act as a @PermitAll Class, Method EJB
firewall and so on. @DenyAll Method EJB
@RolesAllowed Class, Method EJB
Other Security Elements of Web application Table 4: Security Annotation targets in Java EE 6
deployment descriptors
Some of the security annotations can not target a method like
Other elements which we can use in web.xml for security purposes
@DeclareRoles while some other can target both methods and classes
which are listed in the Table 2.
like @PermitAll. Annotation applied on a method will override the
Element Description class level annotations. For example if we apply
security-role Each role must be referenced in a security-role tag before it can be used
@RolesAllowed(employee) on an EJB class, and we apply
in the auth-constraint element of a security-constraint. For example: @RolesAllowed(manager) on one specific method of that EJB, only
<security-role>
<description>All Manager </description> admin role will be able to invoke the marked method while all other
<role-name>manager</role-name>
</security-role> methods will be available to the employee role.
session-config To specify for how long a session should remain valid. For example:
<session-config> A role can be mapped to one or more specific principals, groups,
<session-timeout>120</session-timeout>
</session-config> or to both of them. The principal or group names must be valid in
the specified security realm. The role name we use in the mapping
run-as To use an specific internal role for any out going call from the Servlet.
<run-as> element must match the role-name in the security-role element of the
<role-name>internal_role</role-name>
</run-as>
deployment descriptor [web.xml, ejb-jar.xml] or the role name defined
This element resides inside the Servlet tag. in the @DeclareRoles annotation.
Programmatic Security in Web Module contains standard EJB module deployment elements and vendor
We can access some of the container security context programmatically specific information.
from our Java source code. Table 5 shows the seven methods of
During this section we assume we have an Entity Bean named
HTTPServletRequest class which we can use to extract security related
Employee as follows:
attributes of the request and decide manually about how to process the
request. Listing 3: Sample Employee EJB
@Entity
Method Descriptions public class Employee implements Serializable {
public String getName() {
String getRemoteUser() If the user is authenticated returns the username otherwise
return name;
returns null. }
public void promote(Position toPosition) {
boolean Returns whether the current user has the specified roles or not. //promote the emplyee
isUserInRole(String role)
}
Principal Returns a java.security.Principal object containing the public List<EvaluationRecords> getEvaluationRecords() {
getUserPrincipal() name of the current authenticated user. List<EvaluationRecords> evalRecord;
//return a list containing all
String getAuthType() Returns a String containing authentication method used to // EvaluationRecords of
protect this application. //this employee
return evalRecord;
void login(String This method authenticates the provided username and }
username, String password against the security realm which the application is public List<EvaluationRecords> getEvaluationRecords(Date from, Date to)
password) {
configured to use. We can say this method does anything that
the BASIC or FORM authentication does but gives the developer List<EvaluationRecords> evalRecord;
//return a list containin all
total control over how it is going to happen.
//productivity evaluation of
//this employee in the given time range
Void logout() Establish null as the value returned when getUserPrincipal, return evalRecord;
getRemoteUser, and getAuthType is called on the request. }
@Id
String getScheme() Returns the schema portion of the URL, for example HTTP or private Integer id;
HTTPS. public Employee() {
}
Table 5: Programmatic Security functionalities in Web modules }
The following snippet shows how we check the user role and decide
where to redirect him. Now in the standard deployment descriptor we have can have
something like the following snippet to restrict execution of the
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
Employee Bean methods to certain roles:
throws ServletException, IOException {
Geronimo: (1) Adding role mapping using the same syntax as geronimo-web.xml @Stateless
openejb-jar.xml public class EmployeeServiceBean
(2) Adding web services security using web-service-security subelement of {
the enterprise-beans element. @Resource
SessionContext ctx;
(3) Adding the security realm using the same syntax as public void raiseEmployeePaygrade(int amount, long empID){
geronimo-web.xml Employee employee = null;
//find the employee
JBoss: jboss.xml (1) Specifying the security domain similar to jboss-web.xml String raisedBy =ctx.getCallerPrincipal().getName();
employee.raisePayGrade(850000, raisedBy);
(2) Adding EJB transport security using the ior-security-config subelement //persist the employee
of the message-driven, ejb, service, and session elements. }
}
Table 6: Different application servers EJB deployment descriptors
In the above sample code we injected the context and then we used
Security Annotation of EJB modules in Java EE 6 it to get the principal name. Then we used it to keep record of who
Java EE provides a rich set of security related annotations for the EJB changed the salary of employee.
modules. Each of these annotations can be applied on one or more
types, as explained previously in Table 3 and Table 4. We can use Around Invoke Interceptors to intercept an EJB business
methods call. Intercepting the call lets us access the method name,
Following snippet shows how we can use these annotations to apply its parameters, EJB context (and therefore isCallerInRole and
the same security restrictions we declared in the deployment descriptor getCallerPrincipal methods). We can perform tasks like security
showed in listing 4 on the entity source code shown in Listing 3. check, logging and auditing or ever changing the values of method
parameters using interceptors.
Listing 5: Using annotations to enforce acces restriction on EJBs
For example, the following snippet specifies the callback handler to Application Server Description
collect user identity information.
GlassFish: Role mapping is similar to other Sun specific deployment
sun-application.xml descriptors.
<callback-handler>
Defining the default security realm is as follow:
security.refcard.SwingCallBackHandler
<realm>
</callback-handler>
jdbc_realm
</realm>
For example if we use the HTTP basic authentication and our Web
Security enforcement in JBoss ACC service client uses the Dispatch client API to access the Web service we
Configuration for the JBoss ACC container is stored in the jboss- we can use a snippet like the following one to include the username
client.xml file. This configuration file provides no further security and password with the right access role to invoke a Web service.
customization for the application client.
sourceDispatch.getRequestContext().put(Dispatch.USERNAME_PROPERTY,user);
sourceDispatch.getRequestContext().put(Dispatch.PASSWORD_PROPERTY,password);
DEFINING SECURITY IN ENTERPRISE APPLICATION LEVEL
The user and the password should be valid in the configured realm of
As we saw in the Figure 3, the enterprise application archive (EAR) file Web application and should have access right to the endpoint URL.
can contain multiple modules intended to be deployed into different
containers like Web, EJB or ACC. This EAR module has the deployment
descriptor of its ow which we can use to include the share deployment Another way of authenticating the client to the server in HTTP level is
plan details in addition to EAR specific declarations.
using the Authenticator class which provides more functionalities and
flexibilities. For more information about the authenticator class check
http://java.sun.com/javase/6/docs/technotes/guides/net/http-auth.html
We can use the application level deployment descriptors to define
roles, include the required role mappings and to specify the default
security realm of all included modules. Web Services Security in EJB Modules
We can expose a Stateless Session Bean as a Web Service and
We can use the standard deployment descriptor to define security therefore we can use all security annotations like @RolesAllowed,
roles. The syntax is the same as what we used in the web.xml and the @PermitAll and their corresponding deployment descriptor elements
ejb-jar.xml. to define its security plan.
Similar to other vendor specific deployment descriptors, we can use But the authentication enforcement of the Web Services is vendor
the application level descriptor to define the application-wide role specific and each vendor uses its own method to define the
mapping and also to define the default security realm for all included authentication, security realms and so on.
modules.
Web Services Authentication in GlassFish
The following table shows how we can use different vendor specific For GlassFish we should specify the authentication method and the
deployment descriptors for role mapping and specifying the default security realm in the sun-ejb-jar.xml. For example, to specify HTTP
security realm and shows what security measures are accessible Basic authentication method and a realm named file_realm as the
through the vendor specific enterprise application deployment security realm for a Web service called Echo we will have something
descriptor. similar to the following snippet.
Web Services Authentication in JBoss For a basic comparison and a quick start for these application servers
To specify the authentication realm for a Web service deployed as a take a look at: http://weblogs.java.net/blog/kalali/archive/2009/11/17/
Stateless Session Bean we can use both annotation and deployment state-open-source-java-ee-application-servers.
#82
CONTENTS INCLUDE:
About Cloud Computing
Usage Scenarios Getting Started with
Aldon Cloud#64Computing
Underlying Concepts
Cost
by...
Upcoming Refcardz
youTechnologies
Data
t toTier
brough Comply.
borate.
Platform Management and more...
Chan
ge. Colla By Daniel Rubio
tion:
dz. com
tegra ternvasll
ABOUT CLOUD COMPUTING one time events. TEN TS
INC
HTML LUD E:
us Ind Anti-PPaat
Basics
Automated growthHTM
ref car
nuorn
Valid
ation one time events, cloud ML
connected to what is now deemed the cloud. Having the capability to support
Java EE Security
Usef
Du
ti
ul M.
computing platforms alsoulfacilitate
#84
Open the gradual growth curves
n an
Page Source
s
Vis it
C
faced by web applications. Tools
Core
By Key
Elem
Patte
has changed substantially in recent years, especially with Structur
E: al Elem ents
INC LUD gration the entrance of service providers like Amazon, Google and Large scale growth scenarios involvingents
specialized
NTS and mor equipment
rdz !
HTML
CO NTE Microsoft. es e... away by
(e.g. load balancers and clusters) are all but abstracted
Continu at Every e chang
m
About ns to isolat
relying on a cloud computing platforms technology.
Software i-patter
space
n
Re fca
e Work
Build
riptio
and Ant
Desc
These companies have a Privat
are in long deployed
trol repos
itory
webmana applications
ge HTM
L BAS
Build
re
Buil Repo
This Refcard active
will introduce are within
to you to cloud riente computing, with an
d units
RATION etc. Some platforms ram support large grapRDBMS deployments.
The src
dy Ha
softw
e ine loping and Java s written in hical on of
INTEG attribute
task-o it all
softwar emphasis onDeve es by
Mainl these
ines providers, so youComm can better understand
also rece JavaScri user interfac web develop and the rris
Vis it
Network Security
codel chang desc
INUOU ding Task Level as the
e code
w ww.dzone.com
Label
Build
manu
al
d tool
depe deplo t need but as if
eve , a ) stalle the same nmen for stan overlap uen
(i.e. , inef Build t, use target enviro Amazon EC2: Industry standard it has
software and uagvirtualization ine. HTM , so <a>< tly are) nest
with terns problem ce pre-in whether dards
ated b></
ory. ns (i.e. Autom Redu ymen
has bec become e with a> is
via pat ticular d deploEAR) in each very little L
Subversion
reposit -patter s that Pay only cieswhat you consume
tagge or Amazons cloud you cho platform
computing
the curr isome
heavily based moron fine. b></ ed insid
lained ) and anti the par solution duce nden For each (e.g. WAR es t
ent stan ose to writ more e imp a></ e
not lega each othe
x b> is
be exp text to fi are al Depeapplication deployment
Web ge until t a
librarifew years agonmen
t enviro was similar that will softwaredard
industry standard and virtualization app
e HTM technology.
orta nt,
tterns to pro Minim packa nden
Mo re
CI can ticular con used can rity all depe all targe
s will L or XHT arent. Reg the HTM l, but r. Tags
etimes Anti-pa they
tend
es, but to most phone services:
y Integ alizeplans with le that
late fialloted resources, ts with an and XHT simplify all help ML, und ardless
L VS
XHTM <a><
in a par hes som
Centr
end,
Binar
pro cess. the practic enti ng incurred costgeme
nt
whether e a single
such
temp
resources on
were consumed
t enviro
nmen
orthenot. Virtualization MLaare your
othe
you prov
erst of L
b></
in muchallows physical piece of hardware to
ide be HTM
rily bad
Mana based
approac ed with the cial, but, implem anding
Creat targe es to actually r web
nden
cy rties are nt
of the a solid L has
into differe coding.resources
necessa pared to
chang
efi Depe prope itting utilized by multiple operating
function systems.simplerThis allows foundati job adm been arou
associat to be ben
er
Ge t
te builds commo
are not Fortuna
late Verifi e comm than on
n com Cloud computing asRun itsremo
known etoday has changed this.
befor alitytohas irably, nd for
They they
etc.
Temp Build (e.g. bandwidth, n memory, CPU) be allocated exclusively to tely exp that som
lts whe
ually,
appear effects. Privat y, contin Every elem mov used
to be, HTML
ecte job e time
ed resu The various resourcesPerfo rm a
consumed by webperio applications
dicall (e.g. nt team
pag
individual operating entsinstances. ed to CSS
system Brow d. Earl
y HTM has expand . Whi
gration
opme because
adverse unintend d Builds sitory Build r to devel common e (HTML . ser ed far le it has don
ous Inte web dev manufacture L had very
Stage Repo
e bandwidth, memory, CPU) areIntegtallied
ration on a per-unit CI serve basis or XHT
produc tinu e Build rm an from
extensio .) All are limited more than e its
e.com
ard ML shar
tern.
ack elopers rs add
Con Refc Privat
(starting from zero) by Perfo all majorated cloud
feedb computing platforms. As a user of Amazons esse
term e, this
on
n. HTM EC2 cloud
ntiallycomputing es certplatform, you are result
is a lack came up ed many com
layout anybody
the pat
occur
gration as based
of the cycl such Build Send
autom as they builds pr L plain ain elem supp
ous Inte tional use and test concepts
soon with clev ort.
Integ
ration ors as ion with text ents in of stan peting
entat
tinu dar er wor standar
ven build include
docum
Con kar
the con s to the
oper
to rate devel
While efer of CI Gene
notion
DZone, Inc.
Cloud Computing
the
s on
expand
ISBN-13: 978-1-934238-71-4
140 Preston Executive Dr. ISBN-10: 1-934238-71-6
Suite 100
50795
Cary, NC 27513