I'm also having similar token issue
I'm using the following in C# and the RestSharp library
it works perfectly in AGOL- and am able to Query data from the FeatureService.
but when using against our Portal it gets a token,
however it is unable to use it for hitting REST endpoints to Query - throws an error.
"{\"error\":{\"code\":498,\"message\":\"Invalid Token\",\"details\":[]}}"
RestRequest r = new RestRequest(tokenUrl);
r.AddParameter("client_id", client_id);
r.AddParameter("client_secret", client_secret);
r.AddParameter("grant_type", "client_credentials");
r.Method = RestSharp.Method.POST;
r.RequestFormat = DataFormat.Json;
RestClient c = new RestClient();
IRestResponse rs = c.Execute(r);
JsonDeserializer a = new JsonDeserializer();
Dictionary<string, string> d = a.Deserialize<Dictionary<string, string>>(rs);
accessToken = d["access_token"];