• Resolved Marc Nilius

    (@zottto)


    Hi!

    Is there any way to restrict a website with your plugin including the REST API, but to bypass these restriction for only one specific endpoint to be able to request this endpoint without authentification?

    Thanks for your help!

    Marc

Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author Kevin Vess

    (@kevinvess)

    Hi– thanks for using Force Login!

    Force Login uses the rest_authentication_errors filter to check for REST API authentication. If no authentication is used, it blocks the request.

    You may also hook into that filter to return some non-empty value to indicate an “okay” state and allow the endpoint to be accessed without authentication; bypassing Force Login.

    For example:

    /**
     * Bypass Force Login to allow for REST API exceptions.
     *
     * @param mixed $result WP_Error if authentication error, null if authentication
     *                      method wasn't used, true if authentication succeeded.
     */
    function my_forcelogin_bypass_rest_api( $result ) {
    
      // Skip if request is authenticated
      if ( ! empty( $result ) ) {
        return $result;
      }
    
      // Allow specific endpoint public access
      //if ( $endpoint ) {
      //  return true;
      //}
    
      return $result;
    }
    add_filter( 'rest_authentication_errors', 'my_forcelogin_bypass_rest_api', 20 );

    As for how to determine if the specific endpoint is being requested, I can’t help with that. I recommend you hire a web developer to code that part.

    Thanks and good luck!

    Thread Starter Marc Nilius

    (@zottto)

    Hi Kevin!

    Thanks for your help! That code snippet worked perfectly, the endpoint check relies on $_SERVER, which hopefully will also work. ??

    Thanks,
    Marc

    Just add it to make it clearer and other users can use this method.

    /**
     * Bypass Force Login to allow for REST API exceptions.
     *
     * @param mixed $result WP_Error if authentication error, null if authentication
     *                      method wasn't used, true if authentication succeeded.
     */
    function my_forcelogin_bypass_rest_api( $result ) {
    
        // Skip if request is authenticated
        if (!empty($result)) {
            return $result;
        }
    
        if ($_SERVER['REQUEST_URI'] == '/wp-json/wp/v2/posts') {
            return true;
        }
    
        return $result;
      }
      add_filter( 'rest_authentication_errors', 'my_forcelogin_bypass_rest_api', 20 );
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Bypassing only specific REST endpoint’ is closed to new replies.