Enterprise Java

What is javax.ws.rs.core.context? [ Part 2 ]

How to use the @Context annotation

In part 1 of What is javax.ws.rs.core.context? you learnt how to use the @Context annotation to retrieve HTTP Header information from an injected instance of the HttpHeaders class and how to retrieve URI information from the UriInfo instance such as URI parameters and variables.

In this article, you will learn about using the @Context annotation with the SecurityContext and the ResourceContext class.

Securing RESTful web services with SecurityContext

To secure a RESTful endpoint you can use the javax.ws.rs.core.SecurityContext interface which provides access to security-related information about the request. The SecurityContext instance enables you to access the following security-related information:

  • The authentication type used to secure the resource, such as CLIENT_CERT_AUTH, FORM_AUTH, and BASIC_AUTH
  • The java.security.Principal instance which is populated with the name of the user making the request
  • If the request was made using HTTPS
  • If the user is included in a given role

To get to the SecurityContext you inject an instance into an instance variable, setter method, or method parameter using the @Context annotation.

Let’s take a look at an example that checks if the current user is in the guest role.

@Path("/security-context")
public class SecurityContextResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response sayHello(
                      final @Context SecurityContext securityContext) {
        return Response.ok(securityContext.isUserInRole("guest")).build();
    }

}

This code snippet shows an instance of SecurityContext being injected into the securityContext parameter using the @Context annotation. Then it checks if the user is in the guest role and returns the result to the caller. A call to http://localhost:8080/rest-server/security-context will return true or false depending on the user involvement in the guest role. In this simple example, it should return false as no roles have been configured.

Retrieving a JAX-RS with ResourceContext

The javax.ws.rs.container.ResourseContext instance provides access to instances of other resource classes. It has two methods: the getResource() method with retrieves a resource or sub-resource and the initResource() which initializes a resource or sub-resource.

Let’s create an example that retrieves a resource that adds two number together.

First, you need calculator resource which has a resource method that adds two values.

@Path("/calculator")
public class CalculatorResource {

    @GET
    @Path("add")
    @Produces(MediaType.APPLICATION_JSON)
    public Integer add(@QueryParam("x") int x, @QueryParam("y") int y) {
        return x + y;
    }

}

This is a simple resource class with a single method that adds together two query parameters and returns the result. We are not going to use this resource directly, although we could via the URL http://localhost:8080/rest-server/calculator/add?x=10&y=50, instead, we are going to locate this resource within another resource method and use its add method.

@Path("/resource-context")
public class ResourceContextResource {

    @GET
    @Path("/add")
    @Produces(MediaType.APPLICATION_JSON)
    public Response get(final @Context ResourceContext resourceContext, 
                        final @Context UriInfo uriInfo) {
        final CalculatorResource calculatorResource = 
          resourceContext.getResource(CalculatorResource.class);
        int x = 
          Integer.valueOf(uriInfo.getQueryParameters().getFirst("x"));
        int y = 
          Integer.valueOf(uriInfo.getQueryParameters().getFirst("y"));
        return Response.ok(calculatorResource.add(x, y)).build();
    }

}

In this resource class, there is one resource method that takes the ResourceContext and UriInfo as parameters. The ResourceContext is used to retrieve the CalculatorResource.class and the UriInfo instance is used to retrieve the two query parameters. Then the add() method on the CalculatorResource class instance is called and the two parameters are passed to the method. The result is of the method is sent back to the caller.

To provoke this method make a call to the URL http://localhost:8080/rest-server/resource-context/add?x=10&y=50.

What Next?

That is all for part 2, in part 3 of What is javax.ws.rs.core.context? you will learn how to use the @Context annotation to inject the RequestConfiguration, Providers, and Application classes.

Code Repository

The source code for this and all my articles is in the readlearncode_articles Github repository.

Reference: What is javax.ws.rs.core.context? [ Part 2 ] from our JCG partner Alex Theedom at the Read Learn Code blog.

Alex Theedom

Alex Theedom is a Senior Java Developer and has recently played a pivotal role in the architectural design and development of a microservice based, custom built lottery and instant win game platform. Alex has experience of Java web application development in a diverse range of fields including finance, e-learning, lottery and software development. He is the co-author of Professional Java EE Design Patterns and many articles.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button