Set up WP Authentication from External API

There’s an existing non-WP site, and I need their users to be able to log in on my new WordPress site with the same credentials they already have.

I have been provided with an endpoint (www.example-api.com/token) and login creds (email and password) which gives out a token (and other details) as the response.

I have been reading on OAuth and most of what I get are resources from problems that are other way around (as in login on a non-WP site using their creds on the WP site). I don’t have access to the other site and I see it needs setting up there so, shall I cross this out?

I’ve stumbled upon overriding the wp_authenticate via a custom plugin, which I’ve already set up but I’m stumped as to what and HOW to even do this.

Any guide or boost for this?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Update: Made a blog post to explain this better 🙂


I was able to do this by WP’s authenticate filter inside a new plugin; most of which is guided by this tutorial by Ben Lobaugh. Major points on the plugin:

  • Make an API call function using cURL (you can get guide codes from Postman upon testing if you don’t know already).
  • Add filter checking if the response from the call says the user is existent and has access (based on user role in my case).
  • Still using the filter, check if the user already has an account on the WP site – if not, create one for them using wp_insert_user. For clarification, I used the email and password verified by the API because WP requires a registered user on its database.
  • If the user already exists on the WP database, make sure their credentials are the same using wp_update_user. These are for cases like when they changed their details on the main non-WP website.
  • Optionally, add a settings page for the plugin. In my case, I created a field for the Request URL by following this tutorial by Bharat Pareek.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x