I have just started to read on OAuth as I need to integrate it within a WordPress web app. As per my understanding of OAuth, signed requests are sent between the client and the server. These signed requests are what authenticates a user/client with the server.

WordPress being a stateless application handles authentication via cookies that are sent with every request. Upon receiving the cookies with the request, WordPress automatically sets up the current user. Thus we can use conditionals like current_user_can() or user object like $current_user within the code for various user capability checks and other user actions.

A client (like an iPhone app) when authenticated via OAuth would not store or send cookies and would expect authorised access via OAuth. Since, there is no transfer of WordPress authentication cookies, WordPress would not set the user up during such requests. I’m aware that I could use wp_set_current_user() to do the same. But I’m not sure whether I need to do that OR should I do that OR my entire understanding of using OAuth with WordPress is flawed? Please help me understand how OAuth could be seamlessly integrated into vanilla WordPress environment? Also, I’m not looking for any existing plugins to do the job.

1 Answer
1

Okay, after your comments, I think I see what you’re asking but I’m not sure, so I’ll make it as generic as possible.

WordPress uses the authenticate filter hook to perform authentication. You can add additional authentication methods by connecting your own functions to this filter.

This is an example of an authentication function. This is a dangerous and dumb example, because it just logs you in as user 1 without any checks at all, but it shows what you need the function to return to authenticate a user.

add_filter('authenticate', 'myplugin_auth_example', 30, 3);
function myplugin_auth_example($user, $username, $password) {
    // if user is already known, return it
    if ( is_a($user, 'WP_User') ) { return $user; }

    // do your authentication via whatever method here
    // bottom line is that you need to get a valid WP_User object and return it

    // this example just gets user number 1 from the database and uses that
    // NOTE: this here is extremely dangerous and stupid, because it just logs everybody in instantly
    $user = new WP_User(1); 
    return $user;

    // if there is an error in authentication, you could do this instead    
    return new WP_Error( 'some_bad_auth_reason', 'Your credentials were invalid.' );

}

Leave a Reply

Your email address will not be published. Required fields are marked *