Authenticating to Google Vault API -- getting 400 response with message: "The user does not belong to a G Suite customer." - google-api

I'm trying to do a simple query from the Google Vault API using JSON credentials provided from the Google API console for a service account. I'm getting a 400 response (Invalid Request / Invalid Argument) with the message:
The user does not belong to a G Suite customer.
Does anyone know what I might be doing wrong? Do I have to augment the JSON with anything to indicate our G Suite Account?
Thanks in advance.
The code's fairly straight forward:
matter_id = 'xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx'
vault = Google::Apis::VaultV1::VaultService.new
scope = 'https://www.googleapis.com/auth/ediscovery.readonly'
vault.authorization = Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: File.open('./xxxxxxxxxx.json'),
scope: scope)
vault.authorization.fetch_access_token!
m = vault.get_matter(matter_id)
Update -- this has been resolved. You have to update sub after you create the credentials to impersonate a user.
matter_id = 'xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx'
vault = Google::Apis::VaultV1::VaultService.new
scope = 'https://www.googleapis.com/auth/ediscovery.readonly'
credentials = Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: File.open('./xxxxxxxxxx.json'),
scope: scope)
credentials.update!(sub: 'user#domain.com')
vault.authorization = credentials
vault.authorization.fetch_access_token!
m = vault.get_matter(matter_id)

Related

Use GetTwitter 1.16.3 processor in Nifi gives error 403 Forbidden

I did read the comments on the similar questions, checked out what the answers propose, followed those in detail. Does not change anything.
As I tried to do exactly the same in Python using the Tweepy library, and that does work fine, I know for sure it must be something at Nifi's side.
I do have elevated access on Twitter, I checked multiple times my tokens, they are correctly filled in.
Anybody a usefull answer?
Python code:
import tweepy
consumer_key = 'xxx'
consumer_secret = 'xxx'
access_token = 'xxx'
access_token_secret = 'xxx'
auth = tweepy.OAuth1UserHandler( consumer_key, consumer_secret, access_token, access_token_secret )
api = tweepy.API(auth, wait_on_rate_limit=True)
for tweet in tweepy.Cursor(api.search_tweets, q="#twitter", count=100, tweet_mode='extended', until = '2022-07-09').items():
text = tweet._json["full_text"]
print(text)
print('\n\n')
Nifi code:
Processor GetTwitter (1.16.3) with consumer_key, consumer_secret, access_token, access_token_secret filled correctly in.
Other elements not changed. Added a wait processor connected with success relation.
!! I retested the same simple flow (getTwitter and Wait processor)in version 1.12.1: result is a 401 error instead of 403(?)

MIP SDK fails to protect files

I'm using MIP file sample command line interface to apply labelling.
When trying to apply a label that has protection set, i got "Label requires ad-hoc protection, but protection has not yet been set" error.
Therefore, I tried protecting the file using "--protect" option and got the following error message:
"Something bad happened: The service didn't accept the auth token. Challenge:['Bearer resource="https://aadrm.com", realm="", authorization="https://login.windows.net/common/oauth2/authorize"'], CorrelationId=ce732e4a-249a-47ec-a7c2-04f4d68357da, CorrelationId.Description=ProtectionEngine, CorrelationId=6ff992dc-91b3-4610-a24d-d57e13902114, CorrelationId.Description=FileHandler"
This is my auth.py file:
def main(argv):
client_id = str(argv[0])
tenant_id = str(argv[1])
secret = str(argv[2])
authority = "https://login.microsoftonline.com/{}".format(tenant_id)
app = msal.ConfidentialClientApplication(client_id, authority=authority, client_credential=secret)
result = None
scope = ["https://psor.o365syncservice.com/.default"]
result = app.acquire_token_silent(scope, account=None)
if not result:
logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
result = app.acquire_token_for_client(scopes=scope)
if "access_token" in result:
sys.stdout.write(result['access_token'])
else:
print(result.get("error"))
print(result.get("error_description"))
print(result.get("correlation_id")) # You may need this when reporting a bug
if __name__ == '__main__':
main(sys.argv[1:])
I tried to change the scope to ["https://aadrm.com/.default"] and then I was able to protect the file, but when I try getting the file status or try applying label on it I get the same error message with bad auth token.
These are the permissions as configured in azure portal:
Thank you
I think that scope you have is incorrect: https://psor.o365syncservice.com/.default
It should be https://syncservice.o365syncservice.com/.default.
A good way to handle this is to just append .default to whatever resource the AcquireToken() call gets in the resource param. Something like this.

"Insufficient permission to access this report." - youtube analytics api

I am trying to run this report:
SCOPES = ['https://www.googleapis.com/auth/yt-analytics.readonly','https://www.googleapis.com/auth/yt-analytics.force-ssl','https://www.googleapis.com/auth/yt-analytics-monetary.readonly','https://www.googleapis.com/auth/youtube.readonly']
API_SERVICE_NAME = 'youtubeAnalytics'
API_VERSION = 'v2'
CLIENT_SECRETS_FILE = '/Users/secret.json'
def initialize_analyticsreporting():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[tools.argparser])
flags = parser.parse_args([])
flow = client.flow_from_clientsecrets(
CLIENT_SECRETS_FILE, scope=SCOPES,
message=tools.message_if_missing(CLIENT_SECRETS_FILE))
storage = file.Storage('analyticsreporting.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = tools.run_flow(flow, storage, flags)
http = credentials.authorize(http=httplib2.Http())
analytics = build('youtubeAnalytics', 'v2', http=http)
return analytics
def execute_api_request(client_library_function, **kwargs):
response = client_library_function(
**kwargs
).execute()
print(response)
youtubeAnalytics = initialize_analyticsreporting()
execute_api_request(
youtubeAnalytics.reports().query,
ids='channel==MINE',
startDate='2020-05-01',
endDate='2020-12-31',
dimensions='video',
metrics='views,likes,dislikes,shares,adImpressions',
maxResults=200,
sort='-views'
)
But I get :
"Insufficient permission to access this report."
I am authenticated with OAuth, I am the content owner but I cant get the adImpressions metric to work.
My end goal is to simply get the impressions of a video using youtube analytics API. I've seen multiple threads on this topic but neither answers the question.
As DalmTo mentioned in the comments:
After adding additional scopes:
SCOPES = ['https://www.googleapis.com/auth/yt-analytics.readonly']
To
SCOPES = ['https://www.googleapis.com/auth/yt-analytics.readonly',
'https://www.googleapis.com/auth/yt-analytics-monetary.readonly',
'https://www.googleapis.com/auth/youtube.readonly']
And reauthenticating - deleting the .dat file, and letting a new one to be created, now I am able to receive the desired metrics.

Execute Google Apps Script via ruby script ( `check_status': notFound: Requested entity was not found. (Google::Apis::ClientError)

I have a google apps script that runs a macro to do things on my google sheet. I want my ruby script to execute the macro in the google sheet.
I am getting authentication issues when trying to execute. the script. I have used the ruby quick-start below.
https://developers.google.com/apps-script/api/quickstart/ruby
and everything works fine but it opens a brand app because thats what the script does. I modified it to target my other script that shows up in the same list on the google webpage. I have already tried this below
https://developers.google.com/apps-script/api/how-tos/execute
Every-time I run it, I get this error
`check_status': notFound: Requested entity was not found. (Google::Apis::ClientError)
Here is my code
require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'fileutils'
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'.freeze
APPLICATION_NAME = 'KPI Macros'.freeze
CREDENTIALS_PATH = 'credentials.json'.freeze
# The file token.yaml stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
TOKEN_PATH = 'token.yaml'.freeze
SCOPE = 'https://www.googleapis.com/auth/spreadsheets.currentonly'.freeze
# Ensure valid credentials, either by restoring from the saved credentials
# files or intitiating an OAuth2 authorization. If authorization is required,
# the user's default browser will be launched to approve the request.
#
# #return [Google::Auth::UserRefreshCredentials] OAuth2 credentials
def authorize
client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)
token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)
authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)
user_id = 'default'
credentials = authorizer.get_credentials(user_id)
print(credentials)
if credentials.nil?
url = authorizer.get_authorization_url(base_url: OOB_URI)
puts 'Open the following URL in the browser and enter the ' \
"resulting code after authorization:\n" + url
code = gets
credentials = authorizer.get_and_store_credentials_from_code(
user_id: user_id, code: code, base_url: OOB_URI
)
end
credentials
end
# Initialize the API
service = Google::Apis::ScriptV1::ScriptService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize
script_id = 'MY SCRIPT ID HERE'
# Make the API request.
request = Google::Apis::ScriptV1::ExecutionRequest.new(
function: 'failedTest'
)
response = service.run_script(script_id, request)
print(response)
Any debugging help would be appreciated.

Using Stored Twitter access_tokens with Twitterizer

I am using C3 & the latest twitterizer api. I have managed to get the user to authenticate & authorize my twitter application after which I persist only the access_token, access_token_secret and access_token_verifier.
The problem I have now is that when the user returns ( at a later stage, cookies removed / expired ), they identify themselves using our own credentials system, and then I attempt to see if their twitter credentials are still valid. I do this by calling the following method
OAuthTokens t = new OAuthTokens();
t.ConsumerKey = "XXX"; // my applications key
t.ConsumerSecret = "XXX";// my applications secret
t.AccessToken = "XXX";// the users token from the DB
t.AccessTokenSecret = "XXX";//the users secret from the DB
TwitterResponse<TwitterUser> resp = TwitterAccount.VerifyCredentials(tokens);
This is the error I get : "error":"Could not authenticate with OAuth.","request":"/1/account/verify_credentials.json"
I know my tokens are valid because if I call this method :
TwitterResponse<TwitterUser> showUserResponse = TwitterUser.Show(tokens, CORRECT_SCREEN_NAME_HERE);
with my screen name passed in and the same OAuth tokens, it returns correctly.
Any Ideas?
C# -> v4.0.30319
Twitterizer -> 2.4.0.2028
In your code, you're defining tokens as t, but when you call VerifyCredentials you're passing it tokens. Is that just an error in your sample code?

Resources