Wordpress - How to use WP-REST API to login user and get user data for Android app?
I found the simplest solution using the WP-REST API plugin,first set this in yours environment :
1.) In your themes functions.php
register API endpoint hooks:
add_action( 'rest_api_init', 'register_api_hooks' );
// API custom endpoints for WP-REST API
function register_api_hooks() {
register_rest_route(
'custom-plugin', '/login/',
array(
'methods' => 'POST',
'callback' => 'login',
)
);
function login() {
$output = array();
// Your logic goes here.
return $output;
}
2.) By default, if you have pretty permalinks enabled, the WordPress REST API “lives” at /wp-json/. Then the API endpoint is accessible at youdomain.com/wp-json/custom-plugin/login
with a POST
request.
Notice that custom-plugin/login is actually defined in register_rest_route in PHP function register_api_hooks()
For API key I am using Wordpress Nonces - pretty straightforward as in my discussion here . I hope these answers are useful for all full stack developers who are new to Wordpress REST API
If you just want to user login and get user details you can use and excellent plugin called "JSON API AUTH"
https://wordpress.org/plugins/json-api-auth/
There are following methods available: validate_auth_cookie
, generate_auth_cookie
, clear_auth_cookie
, get_currentuserinfo
nonce can be created by calling http://localhost/api/get_nonce/?controller=auth&method=generate_auth_cookie
You can then use ‘nonce’ value to generate cookie. http://localhost/api/auth/generate_auth_cookie/?nonce=f4320f4a67&username=Catherine&password=password-here
Use cookie like this with your other controller calls: http://localhost/api/contoller-name/method-name/?cookie=Catherine|1392018917|3ad7b9f1c5c2cccb569c8a82119ca4fd