3 Securing RESTful Web Services Using Basic Authentication

You can refer to the use case description, solution summary, components involved, and the linked documentation resources to secure RESTful web services using basic authentication.

This chapter contains the following sections:

3.1 Use Case: Secure a RESTful Web Service Using Basic Authentication

You can develop a RESTful web service and secure it by attaching an Oracle Web Services Manager (OWSM) basic authentication policy.

Use Case

Secure a RESTful web service using basic authentication.

Implementation Summary

Develop a RESTful web service and secure it by attaching an Oracle Web Services Manager (OWSM) basic authentication policy.

Components
  • Oracle WebLogic Server

  • Oracle Web Services Manager (OWSM)

  • Oracle JDeveloper

Required Documentation

To complete this use case, see the following documentation resources:

This use case demonstrates the steps required to:

  • Create a simple HelloWorld RESTful web service using JDeveloper.

  • Display the name of the authenticated user in the output message using javax.ws.rs.core.SecurityContext.

  • Package the RESTful web service with an Application subclass to define the components of a RESTful web service application deployment and provide additional metadata.

  • Secure all RESTful web services, by default, by defining an OWSM global policy.

  • Deploy the RESTful web service as a WAR file to WebLogic Server using the WebLogic Server Administration Console.

  • Verify the HelloWorld web service using a browser.

3.2 Implementing the Use Case: RESTful Web Service Using Basic Authentication

To implement RESTful web service using basic authentication, develop a RESTful web service and secure it by attaching an Oracle Web Services Manager (OWSM) basic authentication policy.

To implement this use case, complete the following steps in sequence:

3.2.1 Implementing RESTful Web Service Using Basic Authentication- Prerequisites

Before implementing RESTful Web Service by using basic authentication, download and install product components, configure WebLogic domain, start the Administration Server, and get the access to Oracle Enterprise Manager Fusion Middleware Control and Oracle WebLogic Server Administration Console.

Before you begin, ensure that you have performed the following tasks:

  1. Download and install the following product components:
  2. Configure a WebLogic domain.

    For the complete procedure, see "Creating a WebLogic Domain" in Creating WebLogic Domains Using the Configuration Wizard.

  3. Start the Administration Server in the domain.

    For the complete procedure, see "Starting and Stopping Servers" in Administering Server Startup and Shutdown for Oracle WebLogic Server.

  4. Ensure that you can access the following administration tools:
    • Oracle Enterprise Manager Fusion Middleware Control:

      http://localhost:7001/em
      
    • Oracle WebLogic Server Administration Console

      http://localhost:7001/console
      

3.2.2 Securing All RESTful Resources by Default

Before you deploy RESTful resources, first define a global policy to secure all RESTful resources by default.

The following procedure defines an OWSM global policy set and assigns it to all RESTful resources. The oracle/wss_http_token_service_policy policy is attached to the policy configure basic authentication for all RESTful resources.

For more information about the web service WLST commands, see "Web Services WLST Custom WLST Commands" in WLST Command Reference for Infrastructure Components.

To secure all RESTful resources by default:

Note:

For the complete procedure, see "Attaching Policies Globally Using WLST" in Securing Web Services and Managing Policies with Oracle Web Services Manager.

  1. Ensure that the WebLogic Server is running.
  2. Start WLST and connect to the running instance of WebLogic Server, as described in "Accessing the Web Services Custom WLST Commands" in Administering Web Services.
    wls:/offline> connect('weblogic', 'welcome1', 't3://localhost:7001')
    Connecting to t3://localhost:7001 with userid weblogic ...
    Successfully connected to Admin Server "AdminServer" that belongs to domain "base_domain".
     
    Warning: An insecure protocol was used to connect to the
    server. To ensure on-the-wire security, the SSL port or
    Admin port should be used instead.
    
  3. Start a session.
    wls:/base_domain/serverConfig> beginWSMSession()
    Location changed to domainRuntime tree. This is a read-only tree with DomainMBean as the root.
    For more help, use help('domainRuntime')
     
    Session started for modification.
    
  4. Define an OWSM global policy set for all RESTful resources.
    wls:/base_domain/serverConfig> createWSMPolicySet('rest-policy-set','rest-resource', 'Service("*")')
     
    Description defaulted to "Global policy attachments for RESTful Resource resources."
    The policy set was created successfully in the session.
    
  5. Attach the oracle/wss_http_token_service_policy policy to the policy set to require basic authentication for all RESTful resources.
    wls:/base_domain/serverConfig> attachPolicySetPolicy('oracle/wss_http_token_service_policy')
     
    Policy reference "oracle/wss_http_token_service_policy" added.
    
  6. Commit the session.
    wls:/base_domain/serverConfig> commitWSMSession()
     
    The policy set rest-policy-set is valid.
    Creating policy set rest-policy-set in repository.
     
    Session committed successfully.
    

3.2.3 Creating a RESTful Web Service

You can create a simple HelloWorld RESTful web service by using JDeveloper.

Procedure:

Note:

For assistance at anytime when using JDeveloper, press F1 or click Help.

  1. Start JDeveloper.

    For the complete procedure, see "Next Steps After Installing Oracle JDeveloper Studio" in Installing Oracle JDeveloper.

  2. Create an application and project using the Create Custom Application wizard.

    Invoke the Create Custom Application wizard by selecting File > New > Application and then General > Applications > Custom Application.

    • Application Name: RESTfulApplication

    • Project Name: RESTfulService

    • Project Features: Java

    • Default Package: samples.helloworld

    For all other values, accept the defaults.

    For the complete procedure, see "Creating Applications and Projects" in Developing Applications with Oracle JDeveloper.

  3. Create a new Java class using the Create Java Class wizard.

    Invoke the Create Java Class wizard by right-clicking the RESTfulService project and selecting New > Java Class.

    Define the following characteristics:

    • Name: HelloWorldResource

    • Constructors from Superclass: Deselect

    • Implement Abstract Methods: Deselect

    For all other values, accept the defaults.

    For the complete procedure, see "How to Create a New Java Class or Interface" in Developing Applications with Oracle JDeveloper.

  4. Add the hello() method to the Java class, as shown in bold below.
    package samples.helloworld;
    public class HelloWorldResource {
        public String hello() {
            return "Hello!";
        }
    }
    
  5. Create a RESTful service from the Java class using the Create RESTful Service from Java Class wizard.

    Invoke the Create RESTful Service from Java Class wizard by right-clicking HelloWorldResource.java and selecting Create RESTful Service.

    Define the following characteristics:

    • Root Path: helloworld

    • Configure HTTP Methods: hello

      - Type: Get
      - Produces: text/plain
      

    For all other values, accept the defaults.

    The code is updated as follows:

    package samples.helloworld;
     
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
     
    @Path("helloworld")
    public class HelloWorldResource {
     
        @GET
        @Produces("text/plain")
        public String hello() {
            return "Hello!";
        }
    }
    

For the complete procedure, see "Creating a RESTful Web Service" in Developing Applications with Oracle JDeveloper

3.2.4 Authenticating the User Using SecurityContext

You can authenticate a user by using javax.ws.rs.core.SecurityContext.

For more information, see "Securing RESTful Web Services Using SecurityContext" in Developing and Securing RESTful Web Services for Oracle WebLogic Server.

To get the authenticated user using SecurityContext:

  1. Access the SecurityContext by injecting an instance into a class field, setter method, or method parameter using the javax.ws.rs.core.Context annotation.

    Update the hello() method, created in the previous step, to print the authenticated user name obtained using the SecurityContext, as follows:

    package samples.helloworld;
     
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.SecurityContext;
    import javax.ws.rs.core.Context;
    import java.security.Principal;
     
    @Path("helloworld")
    public class HelloWorldResource {
     
        @GET
        @Produces("text/plain")
        public String hello(@Context SecurityContext sc) {
            String user = "";
            if (sc != null) {
                Principal p = sc.getUserPrincipal();
                if (p != null) {
                    user = p.getName();
                }
            }
            return "Hello " + user + "!";
        }
    }
    

3.2.5 Packaging With an Application Subclass

You can create a class that extends javax.ws.rs.core.Application to define the components of a RESTful web service application deployment and provides additional metadata.

For more information, see "Packaging With an Application Subclass" in Developing and Securing RESTful Web Services for Oracle WebLogic Server.

To package the RESTful web service with an Application subclass:

  1. Create a new Java class using the Create Java Class wizard.

    Invoke the Create Java Class wizard by right-clicking the samples.helloworld package and selecting New > Java Class. For assistance at anytime, press F1 or click Help.

    Define the following characteristics:

    • Name: MyApplication

    • Package: samples.helloworld

    • Extends: javax.ws.rs.core.Application

    • Constructors from Superclass: Deselect

    • Implement Abstract Methods: Deselect

    For all other values, accept the defaults.

    For the complete procedure, see "How to Create a New Java Class or Interface" in Developing Applications with Oracle JDeveloper.

  2. Override the getClasses() method to return the list of RESTful web service resources (in this case, HelloWorldResource), by adding the code show in bold below.
    package samples.helloworld;
     
    import javax.ws.rs.core.Application;
    import java.util.HashSet;
    import java.util.Set;
     
    public class MyApplication extends Application {
        public Set<java.lang.Class<?>> getClasses() { 
               Set<java.lang.Class<?>> s = new HashSet<Class<?>>();
               s.add(HelloWorldResource.class);
               return s;
        }
    }
    
  3. Add the javax.ws.rs.ApplicationPath annotation to define the base URI pattern that gets mapped to the servlet. For more information about how this information is used in the base URI of the resource, see "What Happens at Runtime: How the Base URI is Constructed" in Developing and Securing RESTful Web Services for Oracle WebLogic Server.
    package samples.helloworld;
     
    import javax.ws.rs.core.Application;
    import java.util.HashSet;
    import java.util.Set;
     
    import javax.ws.rs.ApplicationPath;
     
    @ApplicationPath("resources")
    public class MyApplication extends Application {
        public Set<java.lang.Class<?>> getClasses() { 
               Set<java.lang.Class<?>> s = new HashSet<Class<?>>();
               s.add(HelloWorldResource.class);
               return s;
        }
    }
    

3.2.6 Deploying the RESTful Web Service

Deploy the RESTful web service application as a WAR file to WebLogic Server.

To deploy the RESTful web service:

  1. Create a deployment profile for the Web application:

    1. Define the profile type and name using the Create Deployment Profile wizard.

      Invoke the Create Deployment Profile wizard by right-clicking on the RESTful Service application and selecting Deploy > New Deployment Profile. For assistance at anytime, press F1 or click Help.

      Define the following characteristics.

      - Profile Type: WAR File

      - Deployment Profile Name: helloworld

    2. Define the context root for the Web application using the Edit WAR Deployment Profile Properties wizard.

      The Edit WAR Deployment Profile Properties wizard is invoked automatically when you click OK in the Create Deployment Profile wizard. For assistance at anytime, press F1 or click Help.

      Define the following characteristics:

      - Specify Java EE Web Context Root: restservice

  2. Deploy the web application with the following characteristics using the Deploy <application> wizard.

    Invoke the Deploy <application> wizard by right-clicking the RESTfulService application and selecting Deploy > helloworld. For assistance at anytime, press F1 or click Help.

    Define the following characteristics:

    • Deployment Action: Deploy to WAR

  3. View the WAR file in your configured project directory. For example:

    c:\JDeveloper\mywork\RESTfulApplication\RESTfulService\deploy\helloworld.war
    
  4. Deploy the WAR file on WebLogic Server. For more information, see "Deploy applications and modules" in Oracle WebLogic Server Administration Console Online Help.

3.3 Verifying the Use Case: RESTful Web Service

You can verify a RESTful web service from a browser. You can test basic and advanced features of your web service by using the Web Services Test Client or Test Web Service page in Fusion Middleware Control.

To access the RESTful web service in a browser, enter the following URL in a browser to test the RESTful web service:

http://<host>:<port>/restservice/resources/helloworld

For example, http://localhost:7001/restservice/resources/helloworld.

Enter the WebLogic Server username and password when prompted. For example, weblogic and welcome1.

The following message is returned in the browser:

Hello weblogic!

You can test basic and advanced features of your web service using the Web Services Test Client or Test Web Service page in Fusion Middleware Control. For more information, see "Testing Web Services" in Administering Web Services.

3.4 Additional Resources for RESTful Web Services Use Case

Additional resources that provide more information about developing and securing RESTful web services and clients.