WordPress / application-passwords

183 stars 47 forks source link

How do I use this plugin with Custom Endpoints? #92

Open harre096 opened 5 years ago

harre096 commented 5 years ago

Hello - I like this extension as it is a reasonable way to add secret-based authentication to wp rest-api. So good work! :)

My goal is to build out some custom endpoints as described on developer.wordpress.org. The issue I am facing is that I cannot seem to find a clear way have my custom routes use application-passwords based authentication.

The readme didn't have anything that seemed to answer my question directly, so I went into the code a bit. Since I want to implement a permissions check, I think I need to use a permission_callback. However, I am not sure what plugin code the permissions_callback should ideally call. If there is a simpler way to do all of this, please let me know. Here is what I scraped together:

function application_password_auth_validation(){
  //Get HTTP request headers 
  $auth = apache_request_headers();
  //Get only Authorization header
  $basicAuth = $auth['Authorization'];
  //Based on functions used in https://github.com/georgestephanis/application-passwords/blob/master/class.application-passwords.php
  $user = Application_Passwords::authenticate( $basicAuth, $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] );
  if ( $user instanceof WP_User ) {
    //get the id use return $user->ID;
    return true;
  } else {
    return false;
  }
}

This can then be used to add Auth when defining custom routes as such

add_action( 'rest_api_init', function () {
  register_rest_route( 'myplugin/v1', '/authorWithAuth/(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
    'permission_callback' => 'application_password_auth_validation',
    ) );
  } );

Let me know what you think would be the best way to address, Thank you for all your work!

willnjl commented 2 years ago

https://wordpress.org/support/topic/how-to-use-permission_callback-with-remote-application-passwords/