dhulipudi / webextest

test
0 stars 0 forks source link

permission check servlet #9

Open dhulipudi opened 4 months ago

dhulipudi commented 4 months ago

import javax.servlet.Servlet; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.servlets.SlingSafeMethodsServlet; import org.osgi.service.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory;

/import com.day.cq.personalization.UserPropertiesUtil;/

/**

======== /////// ==========

The PSCServlet class you provided is a servlet that handles HTTP HEAD requests. It's designed to check if a requested resource exists and if the user has read access to it. This is done by trying to retrieve the resource from the server without actually loading the resource itself. This is useful in scenarios where you want to check permissions without the overhead of loading the resource, which could be large or expensive to compute. Common use cases for this servlet could include:
Checking if a user has access to a file before attempting to download it. Verifying if a user can view a page before redirecting them to it. Checking if a resource exists before attempting to perform operations on it. The statement "This servlet essentially acts as an authorization checker for resources based on their URIs. It's a way to verify if a user has read access to a specific resource without actually retrieving the resource itself." means that the servlet is used to check if a user has the necessary permissions to access a resource. This is done by attempting to retrieve the resource from the server. If the server returns the resource, then the user has read access. If not, then the user does not have read access. This is done without actually loading the resource, which can save bandwidth and processing power. To execute this servlet on your local host, you would need to send a HTTP HEAD request to the servlet's URL. The URL would be your local host's address followed by the path specified in the SERVLET_PATH variable. You would also need to include the uri parameter in your request, which should be the URI of the resource you want to check. If you're using a tool like curl, the command might look something like this:

======== //////

curl -I http://localhost:8080/services/permissionCheck?uri=/path/to/resource

========// The provided Java class PSCServlet is a servlet that extends SlingSafeMethodsServlet, which is a part of the Apache Sling framework. This servlet is designed to handle HTTP HEAD requests in a safe manner, meaning that these requests should not change the state of the server. The PSCServlet class is annotated with @Component to declare it as an OSGi component with the service type of Servlet.class. The property sling.servlet.resourceTypes is set to services/permissionCheck, which means this servlet will be invoked for resources of type services/permissionCheck. The doHead method is the main functionality of this servlet. It takes a SlingHttpServletRequest and a SlingHttpServletResponse as parameters. The purpose of this method is to check if a requested resource exists and if the user has read access to it. Here's a step-by-step breakdown of what the doHead method does:
It logs the entry into the method. It retrieves the uri parameter from the request. If the uri contains a period (.), it splits the uri at the first period and takes the first part as the path_to_resource. It attempts to retrieve the resource at path_to_resource using the getResource method of the ResourceResolver from the request. If the resource exists (i.e., getResource does not return null), it sets the HTTP response status to 200 (OK) and logs a message. If the resource does not exist, it sets the HTTP response status to 401 (Unauthorized) and logs a message. If an IllegalArgumentException is caught (which might occur if the uri is not a valid path), it sets the HTTP response status to 403 (Forbidden) and logs an error message. Finally, it logs the exit from the method. This servlet essentially acts as an authorization checker for resources based on their URIs. It's a way to verify if a user has read access to a specific resource without actually retrieving the resource itself.

=======/// =====

dhulipudi commented 4 months ago

package com.adobe.example;

import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Service; import org.apache.felix.scr.annotations.Property;

import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.SlingSafeMethodsServlet;

import org.slf4j.Logger; import org.slf4j.LoggerFactory;

import javax.jcr.Session;

@Component(metatype=false) @Service public class AuthcheckerServlet extends SlingSafeMethodsServlet {

@Property(value="/bin/permissioncheck")
static final String SERVLET_PATH="sling.servlet.paths";

private Logger logger = LoggerFactory.getLogger(this.getClass());

public void doHead(SlingHttpServletRequest request, SlingHttpServletResponse response) {
 try{
  //retrieve the requested URL
  String uri = request.getParameter("uri");
  //obtain the session from the request
  Session session = request.getResourceResolver().adaptTo(javax.jcr.Session.class);
  //perform the permissions check
  try {
   session.checkPermission(uri, Session.ACTION_READ);
   logger.info("authchecker says OK");
   response.setStatus(SlingHttpServletResponse.SC_OK);
  } catch(Exception e) {
   logger.info("authchecker says READ access DENIED!");
   response.setStatus(SlingHttpServletResponse.SC_FORBIDDEN);
  }
 }catch(Exception e){
  logger.error("authchecker servlet exception: " + e.getMessage());
 }
}

}

dhulipudi commented 4 months ago

=====import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.servlets.SlingSafeMethodsServlet; import org.osgi.service.component.annotations.Component; import org.apache.sling.servlets.annotations.SlingServletPaths;

import javax.jcr.Session; import javax.servlet.Servlet; import javax.servlet.ServletException; import java.io.IOException;

@Component(service = Servlet.class) @SlingServletPaths(value = "/bin/permissioncheck") public class AuthCheckerServlet extends SlingSafeMethodsServlet {

@Override
protected void doHead(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    String uri = request.getParameter("uri");

    // Get the resource resolver
    ResourceResolver resourceResolver = request.getResourceResolver();

    // Get the session from the resource resolver
    Session session = resourceResolver.adaptTo(Session.class);

    // Check if the session has permission to access the requested resource
    try {
        if (session.hasPermission(uri, Session.ACTION_READ)) {
            // If the session has permission, send a 200 response
            response.setStatus(SlingHttpServletResponse.SC_OK);
        } else {
            // If the session does not have permission, send a 403 response
            response.setStatus(SlingHttpServletResponse.SC_FORBIDDEN);
        }
    } catch (Exception e) {
        // If an error occurs, send a 500 response
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

}

-----=============------- To test the AuthCheckerServlet in your local AEM instance, you can use a tool like curl or Postman to send a HEAD request to the servlet. Here's how you can do it:

Using curl === =00000------=== Open a terminal and run the following command:

curl -I -X HEAD 'http://localhost:4502/bin/permissioncheck?uri=/content/your-page-path'

===--

Replace /content/your-page-path with the path of the page you want to check. The -I option tells curl to only request the headers, which is equivalent to making a HEAD request.

Using Postman Open Postman and create a new request. Set the method to HEAD and the URL to http://localhost:4502/bin/permissioncheck?uri=/content/your-page-path. Replace /content/your-page-path with the path of the page you want to check. Then, send the request.

In both cases, you should receive a response with a status code of 200 if the user is authorized to access the page, or a status code of 403 if the user is not authorized.

Please note that you need to be logged in as a user with the necessary permissions to access the page. If you're not logged in, you might receive a 401 Unauthorized response.