Search code examples
wordpressgoogle-chrome-extensiontokenwordpress-rest-api

Make Chrome Extension detect if user is logged in on my Wordpress website


I have a Wordpress website and a Chrome Extension. If the user logs in on the website, I want the Chrome Extension to be aware of that (and vice-versa). The Chrome Extension won't have a login form in it; the user will always log in through the website login form.
When you log in on the website, Wordpress by default sets its authentication cookies to identify the user. What I initially had in mind: I would also like to return some kind of access token, which I would store somewhere where the extension can find it and use it to make authenticated requests to the Wordpress REST API. But.. where do I store it (in a safe manner) so I can find it within the extension?
Perhaps I should try a different approach?

Thank you!


Solution

  • What you could do, the simpler way:

    • create an Ajax action or a REST API route
    • as you can read in the documentation, the authentication is cookie-based. So once the user is logged in from the WordPress login form, the authentication cookie is added to your browsing session
    • without overrides, the cookie will also be forwarded when using JS HTTP queries (eg ajax)
    • your route could check something like is_user_logged_in() or wp_get_current_user() like available methods. And return the result (among other things if needed) to your plugin JS
    • you may need to change the WordPress cookie configuration, so they can be accessed from anywhere (any domain), check this.

    Better way:

    • would be to use a plugin like this to implement REST API Oauth2 authentication
    • user should be able to login directly from the extension window (need development), and then use a refresh token feature to keep the user logged in.
    • I believe you may also need to update your actual login form, if its classic or OAuth rest API login, should be able to send back the required OAuth token (access and refresh tokens), to the frontend (then stored in local storage or else) to be used by the extension. To prevent having to log in twice.