Getting `The OAuth client was not found.` and `invalid client` error when trying to get access token for google cloud logging services in Dart - flutter

I'm following through this link: https://developers.google.com/identity/protocols/oauth2/service-account#httprest_1 in order to have my flutter app log to a log bucket in a google cloud project. Currently getting a
{
"error": "invalid_client",
"error_description": "The OAuth client was not found."
}
when I run the code below to get the access token in dart:
var jsonFile =
await File(jsonPath).readAsString();
var map = jsonDecode(jsonFile);
final jwt = JWT(
{
'iss': map['client_email'],
'sub': map['client_email'],
'aud': map['token_uri'],
'iat': (DateTime.now().millisecondsSinceEpoch / 1000).floor(),
'exp':
(DateTime.now().add(Duration(hours: 1)).millisecondsSinceEpoch / 1000)
.floor(),
},
issuer: map['private_key_id'],
);
final token = jwt.sign(SecretKey(map['private_key']));
print(token);
final accessToken = await http.post(
Uri.parse(map['token_uri']),
headers: {
HttpHeaders.contentTypeHeader: 'application/x-www-form-urlencoded',
},
body: {
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion': token,
},
);
The JSON file is the credentials of a service account with logging admin role in the GCP project.

Invalid client means that the client id or the client secret that you are using are not valid.
As per the official documentation,
When attempting to get an access or refresh token, you will get an
"Invalid client" error if you provide an incorrect OAuth 2.0 Client
Secret. Make sure the client_secret value you're using in access and
refresh token calls is the one for the OAuth 2.0 Client ID being used,
as found in your GCP Credentials page.
Also refer to this SO link Github link for more information.

Related

How to Properly Set Permissions for a Custom Strapi Plugin

Strapi Version: 4.1.5
Operating System: Debian GNU/Linux 9
Database: PostgreSQL 13
Node Version: v14.16.0
NPM Version: 6.14.11
Yarn Version: v1.22.5
Hi everyone, I can’t seem to find consistent information on how to use permissions with a custom plugin in Strapi. I want to make an endpoint available to my front-end (Next.JS) application, but only when the front-end application has authenticated as a user and using the JWT that is returned from authenticating with Strapi. I keep getting a 401 returned.
Here’s what I’m doing:
I used this page to set up authentication in Strapi. I have a user created in Strapi, and from the front-end, I can authenticate and it returns a JWT token. When I set up collection types to only be accessible with the “authenticated” role, I can access those collection types in the api using this JWT token. So all of that works. The problem is that I can’t get this to work with my custom plugin, and I’m not sure why. I still get a 401 error instead.
Here’s how I set up the permissions:
Based on this page, I initially tried to leverage the isAuthenticated permission that the Users & Permissions plugin provides:
{
method: "GET",
path: "/progress",
handler: "memberProgress.getProgress",
config: {
policies: ['plugins::users-permissions.isAuthenticated']
},
},
Unfortunately, this did not work. The server raised an error, saying that this could not be found. So back on the document linked above, I decided to take the approach of creating my own gloabl permission. I created src/policies/is-authenticated.js with the following contents:
module.exports = (policyContext, config, { strapi }) => {
if (policyContext.state.user) { // if a session is open
// go to next policy or reach the controller's action
return true;
}
return false; // If you return nothing, Strapi considers you didn't want to block the request and will let it pass
};
Then, I modified my plugin’s route as follows:
{
method: "GET",
path: "/progress",
handler: "memberProgress.getProgress",
config: {
policies: ['global::is-authenticated']
},
},
This is all based on that document I linked to. Unfortunately, this still does not work. It seems to find the permission (server doesn’t raise an error about it), but when I try to access my plugin’s endpoint with the JWT token, I just get a 401 error.
Here is how I’m trying to access the endpoint on the front-end:
// VERIFIED, auth works and I get the expected jwt
const strapiAuth = await strapiApiAuth();
if ( strapiAuth && strapiAuth.hasOwnProperty("jwt") ) {
try {
const response = await axios.get(
`${process.env.STRAPI_BACKEND_URL}/member-progress/progress?year=2022&name=&pageSize=10&page=1`,
{
headers: {
Accept: "application/json",
Authorization: `Bearer ${strapiAuth.jwt}`
},
timeout: 500,
}
);
console.log(response);
} catch (error) {
// This is where I land with the 401 error
console.log(error);
}
}
Strapi check if you have a valid jwt by default with "authenticated" role, but you must mark the permission to your custom endpoint in "Settings→User & Permission Plugin→Roles" of admin panel also.

How to set request header to access Hasura GraphQL Heroku server in Flutter?

I am not able to send a POST request to my Hasura endpoint from my Flutter client and even from POSTMAN.
Here is my current error:
{"errors":[{"extensions":{"path":"$","code":"invalid-json"},"message":"Error
in $: not enough input"}]}
I added endpoint my_endpoint/v1/graphql and HASURA_GRAPHQL_ADMIN_SECRET which I set in Heroku dashboard. ( This value now shows up on my deployed herokuapp console)
My client is using ferry-graphql like this
Client initClient(String url, String secret) {
final link = HttpLink(
url,
defaultHeaders: {
'x-hasura-admin-secret': secret,
},
);
final cache = Cache();
final client = Client(
link: link,
cache: cache,
);
return client;
}
I am not sure what else I should add for my client request header to access hasura.
Something like this might help you: https://github.com/gql-dart/ferry/issues/95#issuecomment-848735562

invalid Client for exchange code _ identityserver3 _ AppAuth

I'm using AppAuth framework for authentication in my Swift app, I can login but after login and coming back to my app, I can't exchange the code and get error invalid client.
My client configuration is:
var client = new Client
{
ClientId = "IOS.Client",
ClientName = "IOS Client",
RedirectUris = { "com.mysite.accounts:/oauthredirect" },
AllowedGrantTypes = GrantTypes.Code, //AuthorizationCode
AllowedScopes = { "openid", "profile", "offline_access" },
};
I set ClientSecret (SHA-256) and my ClientId is ok but I get error invalid client.
I checked my logs and there is an error: secret validators could not validate secret
what's wrong?
IIRC in IS3 you had to set a client secret. We didn't allow empty ones.
Either you set a secret on client and server, or upgrade to IS4 - IS3 is deprecated since quite some time.
When using IdentityServer3 and AppAuth you should not use special characters in ClientSecret and set your grant AuthorizationCodeWithProofKey.
this link is useful

OneDrive API: Unauthenticated, Must be authenticated to use '/drive' syntax

I am using OneDrive api to upload files in my Ruby on Rails application and OneDrive API started giving the unauthenticated error on uploading file using the endpoint /drive/root:/#{filename}:/content. The error is given below:
{"error"=>{"code"=>"unauthenticated", "message"=>"Must be authenticated to use '/drive' syntax"}}
Then I got a new refresh_token by following the OneDrive Docs using scope files.readwrite offline_access.
For OneDrive authentication, I am sending POST request to the endpoint https://login.microsoftonline.com/common/oauth2/v2.0/token to get access_token using the refresh_token with the following headers and body:
headers = { 'Content-Type' => 'application/x-www-form-urlencoded' }
body = {
'client_id' => "<Client ID>",
'grant_type' => "refresh_token",
'redirect_uri' => "<Redirect URI>",
'client_secret' => "<Client Secret>",
'refresh_token' => "<Refresh Token>",
}
Am I using the correct endpoint to get access_token from refresh_token?
The base uri I am using to upload files to OneDrive is https://api.onedrive.com/v1.0
Can anyone please help me why I am I getting unauthenticated error or how can I use '/drive' syntax for authentication?
Thanks in advance!
Solved:
In my case, I was using "Code flow" for the Authentication and using the following url to get code in parameter:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=CLIENT_ID&scope=files.readwrite offline_access&response_type=code&redirect_uri=REDIRECT_URI
Visiting the above url opened the redirect url with a long code parameter which I was using to get access_token and refresh_token but that access_token was not working on uploading files to OneDrive and retuning "unauthenticated" error mentioned in question.
After doing research, I found that the url I am using to get code for OneDrive authentication is for Microsoft Graph. The correct url for Microsoft Account is given below:
https://login.live.com/oauth20_authorize.srf?client_id=CLIENT_ID&scope=onedrive.readwrite offline_access&response_type=code&redirect_uri=REDIRECT_URI
Visiting the above url in browser redirected me to the page with code parameter as well but it was small code like K9vb4e786-afg6-1a3b-1234-12abc01234ca.
I used this code to get access_token and refresh_token using the below POST request:
body = {
client_id: "CLIENT_ID",
redirect_uri: "REDIRECT_URI",
client_secret: "CLIENT_SECRET",
code: "CODE",
grant_type: "authorization_code"
}
headers = { 'Content-Type' => 'application/x-www-form-urlencoded' }
r=HTTParty.post('https://login.live.com/oauth20_token.srf', headers: headers, body: body)
This request returned access_token and refresh_token in response. I used this refresh_token to get an access_token in each request and file uploaded successfully.
Conclusion: I was using Microsoft Graph authentication process ie, https://learn.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/graph-oauth which was incorrect. Then I followed Microsoft Account authentication ie, https://learn.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/msa-oauth which resolved the issue.
Update:
Later I used my Office-365 business account for OneDrive file uploading. For this account, OneDrive authentication process is different ie, https://learn.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/aad-oauth and it worked.

Sentry api authentication issue

I am trying to get all the issues with respect to a project by exposing the sentry api hosted on a private server but getting below response even after using basic auth.
{
"detail": "Authentication credentials were not provided."
}
And after generating api key, getting invalid key.
Thanks
You should add this header:
header = {'Authorization': 'Bearer TOKEN'}
to your request.