Tmeister / wp-api-jwt-auth

A simple plugin to add JSON Web Token (JWT) Authentication to WP REST API
GNU General Public License v2.0
558 stars 161 forks source link

empty_username when I try to get an authentication token #119

Closed Luc45 closed 6 years ago

Luc45 commented 6 years ago

Hello,

When I try to send a POST to http://site.localhost/wp-json/jwt-auth/v1/token with username and password headers, both with correct admin login data, I get a 403 response like this:

{"code":"[jwt_auth] empty_username","message":"ERROR<\/strong>: The username field is empty.","data":{"status":403}}

chrome_2018-07-28_19-23-02

Configs:

I have:

What am I doing wrong?

Luc45 commented 6 years ago

I found out.

I was sending Authorization as Header, it is supposed to go into body as form-data. In Curl, it translates to this:

    /**
    *   Generate a JWT token for future API calls to WordPress
    */
    private function getToken() {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL,'http://site.localhost/wp-json/jwt-auth/v1/token');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "username=admin&password=Str0ngPass");

        // receive server response ...
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $server_output = curl_exec ($ch);
        if ($server_output === false) {
            die('Error getting JWT token on WordPress for API integration.');
        }
        $server_output = json_decode($server_output);

        if ($server_output === null && json_last_error() !== JSON_ERROR_NONE) {
            die('Invalid response getting JWT token on WordPress for API integration.');
        }

        if (!empty($server_output->token)) {
            $this->token = $server_output->token; # Token is here
            curl_close ($ch);
            return true;
        } else {
            die('Invalid response getting JWT token on WordPress for API integration.');
        }
        return false;
    }
yonahrodrigues commented 2 years ago

my solution from this problem in react: export function TOKEN_POST(body) { return { url: API_URL + "/jwt-auth/v1/token", options: { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }, }; }