coinbase oauth2 sometimes failed to renew access token (using refresh token) - authentication

I am integrating coinbase in an iOS app and I am using Oauth2 to authenticate. I am able to get the access token after going through the usual workflow. I have also taken care to attempt refresh my access token whenever any requests hit a 401 (upon expiration) by calling this:
POST https://coinbase.com/oauth/token
Data:
grant_type=refresh_token&refresh_token=abcd1234&client_id=theclientid&client_secret=somesecretid
It works for a while but then from time to time, it would fail with a request response:
NSHTTPURLResponse: 0x15eb2730
{ URL: https://coinbase.com/oauth/token } { status code: 401, headers {
"CF-RAY" = "f67d477aae4052e-YYZ";
"Cache-Control" = "no-store";
Connection = "keep-alive";
"Content-Type" = "application/json; charset=utf-8";
Date = "Sun, 02 Feb 2014 15:14:14 GMT";
Pragma = "no-cache";
Server = "cloudflare-nginx";
"Set-Cookie" = "__cfduid=<some long alpha-numeric string>; expires=Mon, 23-Dec-2019 23:50:00 GMT; path=/; domain=.coinbase.com; HttpOnly";
Status = "401 Unauthorized";
"Strict-Transport-Security" = "max-age=31536000";
"Transfer-Encoding" = Identity;
Vary = "Accept-Encoding";
"Www-Authenticate" = "Bearer realm=\"Doorkeeper\", error=\"invalid_request\", error_description=\"The request is missing a required parameter, includes an unsupported parameter value, or is otherwise malformed.\"";
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = SAMEORIGIN;
"X-Rack-Cache" = "invalidate, pass";
"X-Request-Id" = "<some long alpha-numeric string>";
"X-Runtime" = "0.012066";
"X-Ua-Compatible" = "IE=Edge,chrome=1";
} }
Has anyone encounter this error before? I have assume the request URL is correct always. I am not sure why it would complained about "missing required parameter" or "unsupported parameter". I havent figured out a pattern of failure yet. Hopefully, someone out there may have seen this before.

I haven't been able to find any documentation directly about refresh_token requests, but I think you're supposed to also include the redirect_uri in your refresh_token request (based on this: https://coinbase.com/docs/api/authentication#collapse2).
Also, I noticed that my official coinbase app required a re-auth a few days ago, but when I log in to my coinbase account, it says that the app was authorized 25 days ago. So, perhaps even the request_tokens have a timeout? Did your request_token request fail after not using the app for a while?
Or maybe coinbase reset something and invalidated all of their access_tokens and refresh_tokens because my app, which was previously working fine as far as refresh_tokens, is now failing on the refresh_token request.
So, I would suggest having your app re-authorize when this happens, and get a new access_token and refresh_token, since I think that's what the official coinbase app does.

Related

OAuth2: Unable to Authenticate API request

Been tasked to export forms and items from Podio using the API. Trying to do this with straight Python and Requests instead of the canned API tool. Am successful at retrieving the access and refresh tokens, but am unable to make the simplest Get request. The response has the error:
"error_description":"Authentication as None is not allowed for this method"
Tried this with 2 versions of using OAuth2 in Requests, both return that response.
What is it trying to tell me? Aside from giving the token, is there any other authentication attributes required?
client = BackendApplicationClient(client_id=CLIENT_ID)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=auth_url, client_id=CLIENT_ID,
client_secret=CLIENT_SECRET)
print('token:', token)
access_token = token["access_token"]
api_url = base_url + 'user/status'
r = oauth.get(api_url)
print(r.text)
headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
"Authorization": "Bearer " + token["access_token"]}
response = requests.get(api_url, headers=headers, verify=True)
print(response.text)
Here is full response:
{"error_parameters":{},"error_detail":null,"error_propagate":false,"request":{"url":"http://api.podio.com/user/status","query_string":"","method":"GET"},"error_description":"Authentication as None is not allowed for this method","error":"forbidden"}

Invalid Client with paypal api, client authentication failed using HTTPoison.post!/3

I am using HTTPoison to send request to the Paypal api. Here is the paypal documentation for using its api for logging in: https://developer.paypal.com/docs/log-in-with-paypal/integrate/
When I get the code, and try to exchange it for an access token, I get this error: "{\"error\":\"invalid_client\",\"error_description\":\"Client Authentication failed\"}",
Here is how HTTPoison.post!/3 post request:
url = "https://api-m.sandbox.paypal.com/v1/oauth2/token"
headers = [
Authorization: "Basic #{ClientID}:#{Secret}"
]
body = "grant_type=authorization_code&code=#{code}"
HTTPoison.post!(url, body, headers)
This shows the a status_code: 401 and {\"error\":\"invalid_client\",\"error_description\":\"Client Authentication failed\"}", error.. How can this issue be solved?
HTTP Basic Authentication requires the value to be base-64 encoded. Try doing that:
Authorization: "Basic " <> Base.encode64("#{ClientID}:#{Secret}")

xero api fails with unauthorized (401 or 403) after calling auth, refresh and gettenants when calling getinvoices

I'm a rank noob at this, so excuse my ignorance. I've got an MVC web application to login, get the access and refresh tokens, and tenant list OK. I can even get it to refresh the refresh token. No problems.
When I try to run the GetInvoices endpoint either directly or via the sdk, I get 403 (skd) or 401 from the direct api call.
From the latest run with direct call I get this response
{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content:
System.Net.Http.HttpConnectionResponseContent, Headers:
{
Server: nginx
Strict-Transport-Security: max-age=31536000
WWW-Authenticate: OAuth Realm="api.xero.com"
Cache-Control: no-store, no-cache, max-age=0
Pragma: no-cache
Date: Wed, 21 Jul 2021 11:19:56 GMT
Connection: close
X-Client-TLS-ver: tls1.2
Content-Type: text/html; charset=utf-8
Content-Length: 95
Expires: Wed, 21 Jul 2021 11:19:56 GMT
}, Trailing Headers:
{
}}
I know that the access token and tenant id used in the GetInvoices step are correct because I checked them against the values pulled in from the auth steps character by character.
The app is being run in Visual Studio 2019, using the self-signed development SSL certificate.
Why is it rejecting the request?
my controllers have the following
private static readonly string Scopes = "openid offline_access profile email accounting.transactions accounting.contacts accounting.attachments";
private static readonly string Scopes = "openid offline_access profile email accounting.transactions accounting.contacts accounting.attachments";
string[] tenant = (string[])TempData.Peek("tenant");
var client = new HttpClient();
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("summaryOnly", "true"),
});
client.DefaultRequestHeaders.Add("Authorization", (string)TempData.Peek("accessToken"));
client.DefaultRequestHeaders.Add("Xero-Tenant-Id", tenant[0]);
client.DefaultRequestHeaders.Add("Accept", "application/json");
var response = await client.PostAsync("https://api.xero.com/api.xro/2.0/Invoices", formContent);
The SDK should handle this for you in the helper methods for the client and OAuth flow but i've included what looks like is missing from just a raw API call below.
Core API call - looks like you need to prefix the token with the Bearer string.
Authorization: "Bearer " + access_token
If you are wanting to use the SDK note that there is a sub Nuget package for OAuth helpers that will help you obtain an access token which you need to pass to core api calls.
https://github.com/XeroAPI/Xero-NetStandard/tree/master/Xero.NetStandard.OAuth2Client
(DOH!) The Tenant returns an Id and a TenantId. I was using the Id.
Thanks to SerKnight and droopsnoot for helping.
I've added code from the OAuth2. The help does not mention to get and cast the return type of RequestAcessTokenAsync.
XeroOAuth2Token authToken = (XeroOAuth2Token)await client.RequestAccessTokenAsync(authorisationCode);
also to check the state on return, you must set in xconfig. mine reads
XeroConfiguration xconfig = new()
{
ClientId = Global.XeroClientID,
ClientSecret = Global.XeroClientSecret,
CallbackUri = new Uri(Global.RedirectURI),
Scope = Global.XeroScopes,
State = Global.XeroState
};
var client = new XeroClient(xconfig);
return Redirect(client.BuildLoginUri());

jwksError: Not Found thrown by jwks-rsa module during GET request with auth bearer token to protected api

An error - “jwksError: Not Found” is thrown when I make a get request with the correct bearer token in the request header to my protected API. I’ve followed the start up guide to create the jwtCheck helper function that I pass to all my routes to protect them. I need help clarifying what this error actually means thanks!
Here I define the helper function jwtCheck which will be used to secure all routes.
var jwtCheck = jwt({
secret: jwksClient.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: https://${auth0Domain}/.well-known/jwks.json,
}),
algorithms: ['RS256'],
issuer: https://${auth0Domain}/,
audience: auth0ApiIdentifier,
});
Then I protect my api using jwtCheck defined above like so. After which the api will throw an Unauthorized Error if one tries to send http requests to it without a header in the request with the auth bearer token.
const app = express();
...
app.use(jwtCheck);
...
I get new Bearer tokens by sending a POST request to auth0apiIdentifier/oauth/token and putting the following in the req body:
{
"client_id":id,
"client_secret":secret,
"audience":auth0apiIdentifier,
"grant_type":"client_credentials"
}
After sending the get request via postman with the appropriate bearer token in place, rwks-rsa module throws the subsequent error:
JwksError: Not found.
at ../server/node_modules/jwks-rsa/lib/JwksClient.js:119:23
at ../server/node_modules/jwks-rsa/lib/wrappers/request.js:36:12
at processTicksAndRejections (internal/process/task_queues.js:93:5)
Img 1 - POST request to get new auth Bearer token from Auth0
Img 2 - GET request sent with postman and corresponding error thrown by jwks-rsa module.
I've fixed it! The error was way too ambiguous but after desperation set in, I checked my configs again and I found that I included a "/" at the end of my auth0apiIdentifier, this allowed a "//" in the jwksUri which caused the issue. Solving this typo was my fix.
Check your code guys! Peace!

JWT validation with external authority doesn't work. ASP .NET Core 3.0

I am trying to authorize my requests using external service with IdentityServer4. I use following code
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = Configuration["IdentityUrl"];
options.RequireHttpsMetadata = false;
options.Audience = "myapi";
});
I got my token using token client
var tokenResponse = await tokenClient.RequestPasswordTokenAsync(
new PasswordTokenRequest
{
ClientId = clientId,
ClientSecret = clientSecret,
GrantType = GrantTypes.Password,
Address = discoveryDocument.TokenEndpoint,
UserName = user.UserName,
Password = user.PasswordHash,
});
It works and gives me token, but then when I try to authorize any request by including this token into authorization header it gives me 401 with no explanation. I don't see anything in output of either idenity server application or my client application.
This is what I do in postman to test authorization
Any ideas on what is wrong and how to debug it?
Try to see what the logs says?
Or try to set this one to true in the AddJwtBearer options and then look at the response from the API to see if it contains some additional details about the failure.
options.IncludeErrorDetails = true;
It it works you should see an additional WWW-authenticate header, like this one:
HTTP/1.1 401 Unauthorized
Date: Sun, 02 Aug 2020 11:19:06 GMT
WWW-Authenticate: Bearer error="invalid_token", error_description="The signature is invalid"