Search code examples
wordpressangularwp-api

Custom wordpress login with API Rest and angular


is there a way to create a Custom login with the API Rest of Wordpress and angular.

Currently I'm using the WP REST API - OAuth 1.0a Server plugin but I can´t figure out how to do it

Or maybe its posible using the two methods (Basic Authentication and OAuth)?

I would appreciate any help


Solution

  • I have been wrestling with this the past couple weeks. It kind of depends on your use case.

    First, don't use Basic Auth. It's insecure and for development only. Not worth the time to set up.

    OAuth (I think) is for when you already have a repository of users somewhere, and those users want to give your app approval to access their info, create an account for them, etc. Think of a "Login with Faceook!" button or something, that's OAuth. Could be wrong but I don't think that's what you want.

    What I landed on, and what I think you are asking for, was JWT or JSON Web Token Auth. This is best for me because I want users to be able to create new user accounts and login to them completely within the app.

    First, install the JWT Authentication for WP-API plugin:

    https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/

    This will expose a new endpoint for JWT authentication in the REST API. You will ping that endpoint with user credentials, and get a token response. You then store that token somehow (I'm currently using localStorage) and append it to the request headers of every request that requires permissions. De facto you are logged in! See the plugin docs for details. The example code for attaching the request is in AngJS, not Ang2/4, but the concept is the same. Here's an example from a service that posts a comment.

    postComment(comment): any {
    
    let headers = new Headers({ 'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('currentUser')).token});
    let options = new RequestOptions({ headers: headers });
    
    return this.http
      .post(this._wpBase + "comments", comment, options)
      .subscribe((res: Response) => {
        res.json();
      });
    }
    

    There is probably a fancier, global way to do this but I am still figuring it all out. Hope this is helpful!