Authentication for a mobile app connected via wp-rest api?

I’m not an expert of mobile apps, but as far as I know cookies don’t play well with mobile apps.

I’m working on a similar project (Angular Frontend – WordPress Backend).
Outh is by far the most secure way to go, but it’s rather complicated.
I’m using the wp-api-jwt-auth plugin instead.

If you configure it properly it works quite well.

As an example I share my angular code for user login:

// auth.service.ts

logIn(username: string, password: string, persist?: boolean): Observable<boolean>
{
    persist = persist || false;
    return this.http.post<IUser>(
        API_BASE_DOMAIN + API_BASE_PATH + '/jwt-auth/v1/token',
        { username: username, password: password, remember: persist },
        {
            withCredentials: true, // Send cookies
        }
    ).map(response  => {
        // login successful if there's a jwt token in the response
        if (response.token)
        {
            // set current user data
            this.currentUser = response;

            // store username and jwt token in local storage to keep user logged in between page refreshes
            let storage = (persist) ? localStorage : sessionStorage;
            storage.setItem('currentUser', JSON.stringify(this.currentUser));

            // return true to indicate successful login
            return true;
        }
        else
        {
            // return false to indicate failed login
            return false;
        }
    },
    error => {
        console.log(error);
        return false;
    });
}

On the frontend I use auth0/jwt-auth to handle proper headers/token injection.

Hope this helps

Leave a Comment