Register/login user with Wordpress JSON API

I was able to figure out both login and signup using @Salam El-Bannas' link, in case any one still needs this here you go:

All through you need two plugins to get the job done:

WordPress JSON API plugin

and

JSON API User

  1. For registration of users: You need nonce ID which will be a part of the registration params in the GET url process (this is provided by the plugins). Read @Salam El-Bannas' link for more understanding. The methodology i used in android was that immediately the page loads I block the UI with "Connecting..." message while in the background am getting the nonce ID once its done the UI Blocking disappears and the nonce ID is added to a special non-editable EditText field created for the nonce ID, the user then enters his/her required credentials and I authenticate that its valid before connecting to the server using the nonce ID i got. the result from the server is JSON so i can handle the rest in android code using volley and GSON.

  2. For Login of users: You only need cookies ID generated by the plugin eg in my case http://localhost/mylocalhost/my_api_base/user/generate_auth_cookie/?insecure=cool&[email protected]&password=xxxv678

and the result was this json;

{"status":"ok","cookie":"xxxx|1486130938|Ot6yAX7iU773JnQ2zfE8sdmjt09LhHqDKSYBqtekuha|7fe58a35ab9f260c9bced9148f5cf9ae3ab56c16d7d9ce3b2db7da651d4d937d","cookie_name":"wordpress_logged_in_4132d8131ebbc6760d21627637bd4b20","user":{"id":1,"username":"administrator","nicename":"administrator","email":"[email protected]","url":"","registered":"2016-11-02 17:46:19","displayname":"xxxx","firstname":"","lastname":"","nickname":"xxxxwedds","description":"","capabilities":"","avatar":null}}

then you have to read this nice tutorial to use the resulting JSON in android (that's if you are new to android login) else just use your discretion.

Its really really really simple and interesting once you follow my lined up process.


1.Paste Following code in your themes function.php file.

2.Make sure that WP-REST-API plugin Should be installed on wordpress site

add_action( 'rest_api_init', 'register_api_hooks' );

function register_api_hooks() {
  register_rest_route(
    'custom-plugin', '/login/',
    array(
      'methods'  => 'POST',
      'callback' => 'login',
    )
  );
}

function login($request){
    $creds = array();
    $creds['user_login'] = $request["username"];
    $creds['user_password'] =  $request["password"];
    $creds['remember'] = true;
    $user = wp_signon( $creds, false );

    if ( is_wp_error($user) )
      echo $user->get_error_message();

    return $user;
}

add_action( 'after_setup_theme', 'custom_login' );

Then your API will be created as

http://www.url.com/wp-json/custom-plugin/login

Try it with Postman You will get 200 as a response and user info

Tags:

Json

Wordpress