Java Reference
In-Depth Information
Authentication and Authorization in JAX-RS
To enable authentication, you need to modify the
WEB-INF/web.xml
deployment descriptor
of the WAR file your JAX-RS application is deployed in. You enable authorization through
XML or by applying annotations to your JAX-RS resource classes. To see how all this is put
together, let's do a simple example. We have a customer database that allows us to create
new customers by posting an XML document to the JAX-RS resource located by the
@Path("/customers")
annotation. This service is deployed by a scanned
Application
class annotated with
@ApplicationPath("/services")
so the full URI is
/services/cus-
tomers
. We want to secure our customer service so that only administrators are allowed to
create new customers. Let's look at a full XML-based implementation of this example:
<?xml version="1.0"?>
<web-app>
<web-app>
<security-constraint>
<web-resource-collection>
<web-resource-name>
customer creation
</web-resource-name>
<url-pattern>
/services/customers
</url-pattern>
<http-method>
POST
</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>
admin
</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>
BASIC
</auth-method>
<realm-name>
jaxrs
</realm-name>
</login-config>
<security-role>
<role-name>
admin
</role-name>
</security-role>
</web-app>
The
<login-config>
element defines how we want our HTTP requests to be authenticated
for our entire deployment. The
<auth-method>
subelement can be
BASIC
,
DIGEST
, or
CLIENT_CERT
. These values correspond to Basic, Digest, and Client Certificate Authentica-
tion, respectively.
The
<login-config>
element doesn't turn on authentication. By default, any client can ac-
cess any URL provided by your web application with no constraints. To enforce authentica-