How to add security, authentication to my REST service?


  • We developed a REST service and it works. But we need endpoint security. At the moment it is available without any credentials.
  • We do not want to give access to a REST Web service without credentials. 
    How can we force user to send credentials (Basic Auth is ok) to call our service Endpoint?


  • Liferay DXP 7.0


We'll show you how to implement a simple User-permission layer using the sample project.

  1. When you build and deploy (
    liferay-blade-samples/liferay-workspace/apps/rest{7.0}$ ./../../../gradlew deploy

    ) this module and visit http://localhost:8080/o/ : you'll get back the list of users:

    Test Test
  2. Let's update the related method of to look like this:
    	public String getUsers() {
    		PermissionChecker permissionChecker =
    		if (!permissionChecker.isCompanyAdmin()) {
    			throw new WebApplicationException(Response.Status.FORBIDDEN);
    		StringBuilder result = new StringBuilder();
    		for (User user : _userLocalService.getUsers(-1, -1)) {
    		return result.toString();

    As you can see, we're getting the PermissionChecker and checking if the given user is Company Admin. If not, we throw a standard exception that is allowed from JAX-RS applications. (You can google for more details on exception handling).

  3. Redeploy the module and retest. If you visit http://localhost:8080/o/ again, you will get back an empty response and HTTP 403 status. 
  4.  Let's test the service invocation with Basic Auth:
    1. Encode "" with base64: base64 <<< : Result: dGVzdEBsaWZlcmF5LmNvbTp0ZXN0Cg==
    2. Invoke the endpoint:
      curl -H "Authorization: Basic dGVzdEBsaWZlcmF5LmNvbTp0ZXN0Cg==" http://localhost:8080/o/


      Test Test
    3. Repeat the same with a non-omniadmin user: you'll get back an empty response as expected.
  5.  Basic Auth is enabled for this application here:
    1. Similarly, if you want to be able to access the endpoint from your browser with an authenticated user through your session, you can
      A.) Go to System Setting > Foundation > CXF Endpoints > / > and add



      to the "Authentication Verifier Properties" so you'll have both Basic Auth and Portal Session auth verifiers enabled for the sample service.

      auth.verifier.BasicAuthHeaderAuthVerifier.urls.includes=/users/list // or simply "*"
      auth.verifier.PortalSessionAuthVerifier.urls.includes=/users/list // or simply "*"

      B.) Add it to the configuration files of the "rest" sample module
      C.) Go to System Setting > Foundation > Portal Session Auth Verifier: and add "/users/list" to the "URs Includes" property

0 人中有 0 人觉得有帮助