title: Get an OAuth2 access token failed with error message "HTTP/1.1 401 Unauthorized"
body: <p>I am writing OAuth client in JAVA to acquire OAuth token from Central Authentication Service (PingFederate). As this client is standalone utility, there is no application server behind it.</p>
  
  <p>I am trying to achieve : <strong><em>A standalone JAVA client should acquire OAuth token from PingFederate it should allow for some scope, ex. TEST_READ. Once I have access token, I will pass it to resource provider.</em></strong></p>
  
  <p>So, as per the PingFederate document such standalone client should use the Grant Type=Resource Owner Password Credentials and to acquire Oauth token POST request should contains username/password and client id and secret.</p>
  
  <p>When I attempted the same, I received error in response:</p>
  
  <pre><code>HTTP/1.1 401 Unauthorized [Date: Tue, 28 Aug 2018 09:04:50 GMT, Content-Security-Policy: referrer origin, X-Frame-Options: SAMEORIGIN, Cache-Control: no-cache, no-store, Pragma: no-cache, Expires: Thu, 01 Jan 1970 00:00:00 GMT, Content-Type: application/json;charset=utf-8, WWW-Authenticate: basic realm="PF AS Token Endpoints", Set-Cookie: PF=zVXrZpsAmWwrrVkzgltJZ4;Path=/;Secure;HttpOnly, Transfer-Encoding: chunked] org.apache.http.conn.BasicManagedEntity@68c9133c
  </code></pre>
  
  <p>To dig more into it, I checked PingFederate audit.log where I found the log: <code>AS| failure| | invalid_client: client_id value doesn't match HTTP Basic username value| 0</code> </p>
  
  <h2>Here is my JAVA client code</h2>
  
  <pre><code>package com.auth;
  
  import java.io.IOException;
  import java.util.ArrayList;
  import java.util.List;
  import java.util.Map;
  
  import org.apache.commons.codec.binary.Base64;
  import org.apache.http.HttpResponse;
  import org.apache.http.ParseException;
  import org.apache.http.client.ClientProtocolException;
  import org.apache.http.client.entity.UrlEncodedFormEntity;
  import org.apache.http.client.methods.HttpPost;
  import org.apache.http.impl.client.DefaultHttpClient;
  import org.apache.http.message.BasicNameValuePair;
  import org.apache.http.protocol.HTTP;
  import org.apache.http.util.EntityUtils;
  import org.json.simple.parser.JSONParser;
  
  public class OAuth2Client {
  
      public static final String GRANT_TYPE = "grant_type";
      public static final String CLIENT_ID = "client_id";
      public static final String CLIENT_SECRET = "client_secret";
      private static final String AUTHORIZATION = "Authorization";
      public static final String BASIC = "Basic";
      public static final String ACCESS_TOKEN = "access_token";
      public static final String SCOPE = "scope";
  
      public static void main(String[] args) {
          System.out.println(getAccessToken());
      }
  
      public static String getAccessToken() {
          HttpPost post = new HttpPost(
                  "https://localhost:9031/as/token.oauth2");
          String clientId = "OAUTH-CLIENT-TEST";
          String clientSecret = "OAUTH-CLIENT-TEST-SECRET";
          String scope = "TEST_READ";
          String username = "testuser";
          String password = "test#001Pass";
  
          List&lt;BasicNameValuePair&gt; parametersBody = new ArrayList&lt;BasicNameValuePair&gt;();
          parametersBody.add(new BasicNameValuePair(GRANT_TYPE, "password"));
  
          parametersBody.add(new BasicNameValuePair(CLIENT_ID, clientId));
          parametersBody.add(new BasicNameValuePair(CLIENT_SECRET, clientSecret));
          parametersBody.add(new BasicNameValuePair(SCOPE, scope));
  
          DefaultHttpClient client = new DefaultHttpClient();
          HttpResponse response = null;
          String accessToken = null;
          try {
              //post.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
              post.setEntity(new UrlEncodedFormEntity(parametersBody));
  
              post.addHeader(AUTHORIZATION,
                      BASIC + " " + encodeCredentials(username, password));
              post.addHeader("Content-Type", "application/x-www-form-urlencoded");
  
              response = client.execute(post);
  
              int code = response.getStatusLine().getStatusCode();
  
              if (code &gt;= 400) {
                  throw new RuntimeException(
                          "Could not retrieve access token for user: " + username);
              }
              Map&lt;String, String&gt; map = handleJsonResponse(response);
              accessToken = map.get(ACCESS_TOKEN);
          } catch (ClientProtocolException e) {
  
              e.printStackTrace();
          } catch (IOException e) {
  
              e.printStackTrace();
          }
  
          return accessToken;
      }
  
      public static String encodeCredentials(String username, String password) {
          String cred = username + ":" + password;
          String encodedValue = null;
          byte[] encodedBytes = Base64.encodeBase64(cred.getBytes());
          encodedValue = new String(encodedBytes);
          System.out.println("encodedBytes " + new String(encodedBytes));
  
          byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
          System.out.println("decodedBytes " + new String(decodedBytes));
  
          return encodedValue;
  
      }
  
      public static Map handleJsonResponse(HttpResponse response) {
          Map&lt;String, String&gt; responseMap = null;
          String contentType = response.getEntity().getContentType().getValue();
          try {
              responseMap = (Map&lt;String, String&gt;) new JSONParser()
                      .parse(EntityUtils.toString(response.getEntity()));
          } catch (ParseException e) {
              e.printStackTrace();
              throw new RuntimeException();
          } catch (org.json.simple.parser.ParseException e) {
              e.printStackTrace();
              throw new RuntimeException();
          } catch (IOException e) {
              e.printStackTrace();
              throw new RuntimeException();
          } catch (RuntimeException e) {
              System.out.println("Could not parse JSON response");
              throw e;
          }
          System.out.println();
          System.out.println("********** Response Received **********");
          for (Map.Entry&lt;String, String&gt; entry : responseMap.entrySet()) {
              System.out.println(String.format("  %s = %s", entry.getKey(),
                      entry.getValue()));
          }
          return responseMap;
      }
  }
  </code></pre>