Password Grant

Token Request

The Password grant is one of the simplest OAuth grants and involves only one step: the application presents a traditional username and password login form to collect the user’s credentials and makes a POST request to the server to exchange the password for an access token. The POST request that the application makes looks like the example below.

        POST http://<wp_base_url>/wp-json/moserver/token
        Host: authorization-server.com
        Content-type: application/x-www-form-urlencoded

        grant_type=password
        &username=exampleuser
        &password=12345678
        &client_id=xxxxxxxxxx

The POST parameters in this request are explained below.

  • grant_type=password : This tells the server we’re using the Password grant type

  • username : The user’s username that they entered in the application

  • password : The user’s password that they entered in the application

  • client_id : The public identifier of the application that the developer obtained during registration

  • cURL
  • Postman
  • C#
  • Java
  • PHP
  • Python
curl -H "Content-Type:application/x-www-form-urlencoded" -d "grant_type=password&username=<your-wordpress-username>&password=<your-wordpress-password>&client_id=<your-client-id>&client_secret=<your-client-secret>" http://<your-wordpress-domain-name>/wptest/wordpress/wp-json/moserver/token

Click here to download POSTMAN collection export

String getAccessToken()
{
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://YOUR_DOMAIN/wp-json/moserver/token");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
                string json = JsonConvert.SerializeObject(new
                {
                grant_type = "password",
                username = "<<YOUR USER_NAME>>",
                password = "<<YOUR PASSWORD>>",
                client_id = "<<YOUR CLIENT_ID>>",
                client_secret = "<<YOUR CLIENT SECRET>>"
                });
                streamWriter.Write(json);
        }
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        var streamReader = new StreamReader(httpResponse.GetResponseStream());
        var result = streamReader.ReadToEnd();
        dynamic jtoken = JsonConvert.DeserializeObject(result);
        Console.WriteLine(jtoken.access_token);
        return jtoken.access_token;
}
private static String getAccessToken(code, redirectUrl, clientId, clientSecret)
{
        Pattern pat = Pattern.compile(".*\"access_token\"\\s*:\\s*\"([^\"]+)\".*");
        String content = "grant_type=password&username=" + userName + "&password=" + password;
        BufferedReader reader = null;
        HttpURLConnection connection = null;
        String accesstoken = "";
        try {
        URL url = new URL(tokenUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Authorization", "Basic " + authentication);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Accept", "application/json");
        PrintStream os = new PrintStream(connection.getOutputStream());
        os.print(content);
        os.close();
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = null;
        StringWriter out = new StringWriter(connection.getContentLength() > 0 ? connection.getContentLength() : 2048);
        while ((line = reader.readLine()) != null) {
                out.append(line);
        }
        String response = out.toString();
        Matcher matcher = pat.matcher(response);
        if (matcher.matches() && matcher.groupCount() > 0) {
                accesstoken = matcher.group(1);
        }
        connection.disconnect();
        } catch (Exception e) {
        System.out.println("Error : " + e.toString());
        } finally {
        if (reader != null) {
                try {
                reader.close();
                } catch (IOException e) {
                }
        }
        }
        System.out.println(accesstoken);
        return accesstoken;
}
function getAccessToken()
{
        $token_url = "http://YOUR_DOMAIN/wp-json/moserver/token";
        $client_id = "<YOUR CLIENT_ID>";
        $client_secret = "<YOUR CLIENT SECRET>";
    $tokenContent = "grant_type=password&username=<<USERNAME>>&password=<<PASSWORD>>";
    $authorization = base64_encode("$client_id:$client_secret");
    $tokenHeaders = array("Authorization: Basic {$authorization}","Content-Type: application/x-www-form-urlencoded");
    $token = curl_init();
    curl_setopt($token, CURLOPT_URL, $token_url);
    curl_setopt($token, CURLOPT_HTTPHEADER, $tokenHeaders);
    curl_setopt($token, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($token, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($token, CURLOPT_POST, true);
    curl_setopt($token, CURLOPT_POSTFIELDS, $tokenContent);
    $response = curl_exec($token);
    curl_close ($token);
    echo $response;
    return json_decode($response)->access_token;
}
import requests,json
def get_access_token():
        token_url = "http://YOUR_DOMAIN/wp-json/moserver/token"
        resource_url = "http://YOUR_DOMAIN/wp-json/moserver/resource"
        callback_uri = "<<CALL BACK URI>>"
        client_id = '<<CLIENT_ID>>'
        client_secret = '<<CLIENT SECRET>>'
        t_json = {'grant_type':'password','username':'<<USERNAME>>','password':'<<PASSWORD>>','client_id' : client_id,'client_secret' : client_secret}
        response = requests.post(token_url,data=t_json)
        resp = json.loads(response.text)
        access_token = resp["access_token"]
        return access_token

The server replies with an access token in the same format as the other grant types.

For example, the user can be redirected back to callback URL such as

Sample Response:

        https://callback-url?
        #access_token=<access_token>
        &token_type=Bearer
        &expires_in=3600
        &scope=<permissions_requesting>

The client can then use the access_token to access protected resources from Resource server.
Here, is the description for each parameter received in the response.

  • access_token : access token for the Userinfo endpoint.

  • token_type : OAuth 2.0 token type value. The value must be Bearer.

  • expires_in : The expiry time for the access token.

  • scope : One or more space seperated strings which indicates the permission your application requesting.

Resource Request

The UserInfo Endpoint is an OAuth 2.0 Protected Resource that returns Claims about the authenticated End-User. The returned Claims are represented by a JSON object that contains a collection of name and value pairs for the Claims.

The following is a non-formative example of Userinfo Request:

        GET http://<wp_base_url>/wp-json/moserver/userinfo
        Host: server.example.com
        Authorization: Bearer <access_token>
  • cURL
  • Postman
  • C#
  • Java
  • PHP
  • Python
curl -H "Authorization: Bearer <your-access-token>" http://<your-wordpress-domain-name>/wptest/wordpress/wp-json/moserver/resource

Click here to download POSTMAN collection export

void getResources()
{
        String url = "http://YOUR_DOMAIN/wp-json/moserver/resource";
        String respo = string.Empty;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Headers.Add("Authorization", "Bearer "+access_token);
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream stream = response.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream))
        {
                respo = reader.ReadToEnd();
        }
        Console.WriteLine(respo);
}
String getResource(String accesstoken)
{
        BufferedReader reader = null;
        String response = new String();
        try {
        URL url = new URL(resourceuri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Authorization", "Bearer " + accesstoken);
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = null;
        StringWriter out = new StringWriter(connection.getContentLength() > 0 ? connection.getContentLength() : 2048);
        while ((line = reader.readLine()) != null) {
                out.append(line+"
"); } response = out.toString(); System.out.println(response); } catch (Exception e) { System.out.println(e.toString()); } return response; }
function getResource($access_token) {
    $resource_url = "http://YOUR_DOMAIN/wp-json/moserver/resource";
    $header = array("Authorization: Bearer {$access_token}");
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $resource_url,
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_RETURNTRANSFER => true
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    return json_decode($response, true);
}
def get_resource(resource_url, access_token):
        api_call_headers = {'Authorization': 'Bearer ' + access_token}
        api_call_response = requests.get(resource_url, headers=api_call_headers, verify=False)
        print api_call_response.text

Sample Response :
The UserInfo Claims MUST be returned as the members of a JSON object.

        [{
            "id": "1",
            "username": "abc",
            "first_name": "xyz",
            "last_name": "example",
            "picture": "https://example.com/-kwtzesU/photo.jpg",
            "email": "abc@example.com",
            "locale": "en",...
        }]