Authorization Code Grant

Authorization Request

The application first needs to decide which permissions it is requesting, then send the user to a browser to get their permission. To initiate this authorization flow, form a URL as below and redirect the end user's browser to the URL

        GET http://<wp_base_url>/wp-json/moserver/authorize
        ?response_type=code
        &client_id= <client_id_goes_here>
        &redirect_uri= <callback_url>
        &scope= <permissions_requesting>
        &state= <security_token>
  • response_type=code :The type of response you are expecting. To recieve authorization code it must have value code. This tells authorization server that application is initiating authorization flow.

  • client_id :The Client ID provided by the OAuth provider.

  • redirect_uri :Callback Url to which user will be redirected once they allow or disallow the access to your app.

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

  • state :The application generates a random string and includes it in the request. It should then check that the same value is returned after the user authorizes the app.

If the user allows access to your app, thier browser will be redirected to the supplied redirect url and request will include code and state parameters in the query string.

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

Sample Response:

        https://example-app.com/redirect
        ?code=<authorization-code>
        &state=<security_token>
  • The code is Authorization code which can be exchanged for Access token. It is generated by the authorization server and is relatively short lived.

  • The state is the same security token that the application initially set in the request.

Token Request

If the end user granted your app access and you receive an Authorization Code, you can exchange the Authorization Code for an Access Token by making a POST request to the token endpoint.

The following is an example for POST request:

        POST http://<wp_base_url>/wp-json/moserver/token
        Content-Type: application/x-www-form-urlencoded

        grant_type=authorization_code&
        code=<authorization_code>&
        client_id=jkbhih8rew43f&
        client_secret={clientSecret}&
        redirect_uri=<redirect_uri>

Here, is the description for each request parameter.

  • grant_type=authorization_code : The type of grant you are providing. This tells that the application is using authorization code grant type.

  • code : The authorization code recieved in previous step, included here.

  • redirect_uri: The same uri that was provided earlier in the authorization request.

  • client_id : The client ID provided by the OAuth provider.

  • client_secret : The client secret provided by the OAuth provider.

  • cURL
  • Postman
  • C#
  • Java
  • PHP
  • Python
curl -H "Content-Type:application/x-www-form-urlencoded" -d "grant_type=authorization_code&code=876f229bdc53dbff9b58977c8324f1661cd3d3ae&redirect_uri=http://localhost:81/test.php&client_id=adBgNVoaxzHigvkaRHdwPGyBYlRRUo&client_secret=ijjEzrdVTzOwQRVFTUrhODKEIMMYRl" http://localhost:81/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 = "authorization_code",
                client_id = "<<YOUR CLIENT_ID>>",
                client_secret = "<<YOUR CLIENT SECRET>>",
                code = "<<AUTHORIZATION_CODE>>"
            });
            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 String getAccessToken(code, redirectUrl, clientId, clientSecret)
{
        Pattern pat = Pattern.compile(".*\"access_token\"\\s*:\\s*\"([^\"]+)\".*");
        String content = "grant_type=authorization_code&code=" + code + "&redirect_uri=" + redirectUrl + "&client_id=" +clientId+"&client_secret="+clientSecret;
        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($authorization_code, $callback_uri) {
        $token_url = "http://YOUR_DOMAIN/wp-json/moserver/token";
        $client_id = "<YOUR CLIENT_ID>";
        $client_secret = "<YOUR CLIENT SECRET>";
    $authorization = base64_encode("$client_id:$client_secret");
    $header = array("Authorization: Basic {$authorization}","Content-Type: application/x-www-form-urlencoded");
    $content = "grant_type=authorization_code&code=$authorization_code&redirect_uri=$callback_uri";
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $token_url,
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $content
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    if ($response === false) {
        echo "Failed";
        echo curl_error($curl);
        echo "Failed";
    } elseif (json_decode($response)->error) {
        echo "Error:<br />";
        echo $authorization_code;
        echo $response;
    }
    return json_decode($response)->access_token;
}
import requests, json
def get_access_token(authorization_code, callback_uri):
        token_url = "http://YOUR_DOMAIN/wp-json/moserver/token"
        client_id = '<<CLIENT_ID>>'
        client_secret = '<<CLIENT SECRET>>'
        data = {'grant_type': 'authorization_code', 'code': authorization_code, 'redirect_uri': callback_uri}
        print "requesting access token"
        access_token_response = requests.post(token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))
        print "response"
        print access_token_response.headers
        print 'body: ' + access_token_response.text
        tokens = json.loads(access_token_response.text)
        access_token = tokens['access_token']
        print "access token: " + access_token
        return access_token

At the token endpoint all the parameters in the request will be verified ensuring that the code hasn't expired and the client id and secret matches. If the Request is successful, it will generate an access token and return it in the response:

Sample Response:

        HTTP/1.1 200 OK
        Content-Type: application/json
        Cache-Control: no-store
        {
            "access_token":"hkjher92u9eu2u3uihi2eh9293",
            "token_type":"bearer",
            "expires_in":3600,
            "scope":"profile",
            "id_token":""
        }

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.
  • id_token: The ID Token is a security token that contains Claims about the authentication of an End-User by an Authorization Server when using a Client, and potentially other requested Claims

If the request fails the response will have a status of 404 Bad Request and will have the following contents:

"error" : "invalid_request",
"error_description" : "A more detailed description of the error intended for the developer of your app."

Resource Request

If the token request is successful, you will get access_token in the response which can be used to access the protected resources via the API.

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>

The resource server validate and verify the access token and checks if it has not expired. If the resource request is valid the resource server returns the claims which are represented by a JSON object that contains a collection of name and value pairs for the Claims.

  • cURL
  • Postman
  • C#
  • Java
  • PHP
  • Python
curl -H "Authorization: Bearer <access-token>" http://<your-wordpress-domain-name>/wptest/wordpress/wp-json/moserver/resource

Click here to download POSTMAN collection export

void getResources(String access_token) {
        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.

Below is the example:

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