Microsoft Graph API - error 403 "Insufficient privileges to complete the operation" - r

I'm trying to use the AzureR family of R packages to interact with Outlook through the Graph API. Using Microsoft365R I have the following code:
outl <- get_business_outlook(
tenant = tenant_id,
app = client_id,
password = client_secret
)
But this results in a 403 error:
Error in process_response(res, match.arg(http_status_handler), simplify) :
Forbidden (HTTP 403). Failed to complete operation. Message:
Insufficient privileges to complete the operation.
The app in question has the API permissions Mail.ReadWrite, Mail.ReadWriteShared, Mail.Send, Mail.Send.Shared, offline_access, openid, User.Read.
I also tried using the AzureGraph package directly like:
login <- create_graph_login(
tenant = tenant_id,
app = client_id,
password = client_secret
)
This works and I get a token. I then try to extract user information with me <- login$get_user(), but this throws the same 403 error as above. I suspect there is something I need to do to actually authenticate the user, but I can't really figure out what.
I am entirely new to the Graph API so it's very possible that I have missed something obvious. Any help appreciated!

Microsoft365R/AzureGraph author here. In the code you show, both with get_business_onedrive() and create_graph_login(), you are authenticating as the app, not as the user. This means that there is no user account involved, hence you're unable to view user details or send email.
To authenticate as the user, run
# Microsoft365R
get_business_outlook("tenant_id", app="client_id")
# AzureGraph
create_graph_login("tenant_id", app="client_id")
ie, without the password argument. You should know it's working if R opens up a browser window for you to login to Azure (or to show it's successfully logged in).
The latest revision of the AzureAuth package has a vignette that explains a bit more on the various authentication scenarios. AzureAuth::get_azure_token is the underlying function used to obtain an OAuth token by Microsoft365R and AzureGraph, and you can pass down the arguments mentioned in the vignette from get_business_outlook and create_graph_login.

Related

httr::oauth1.0_token returns HTTP 403

I tried to use httr::oauth1.0_token to authenticate against Twitter, but I got an error:
library(httr)
oauth1.0_token(oauth_endpoints("twitter"),
oauth_app("tw", key = Sys.getenv("Twitter_API"),
secret = Sys.getenv("Twitter_Key")))
# Error in init_oauth1.0(self$endpoint, self$app, permission = self$params$permission, :
# Forbidden (HTTP 403).
As I am new to OAuth authentication, I started reading the Twitter Docs and built the authentication dance from scratch.
After a lot of trial and error, I was eventually successful, so I can rule out that something on the twitter app setting end is wrong (that is the endpoint is set up correctly and especially the callback URL is defined properly, furthermore key and secret are the correct ones).
Before filing a bug report, I wanted to double check that I am using oauth1.0_token correctly. Thus, is this a bug or am I the bug?

Getting different errors when try to run report for GA4 with regular account

I am trying to run a simple report on GA4 by using Google Analytics Data API Python client with a regular user credentials:
request = RunReportRequest(
property=f"properties/11111",
dimensions=[Dimension(name=f['name']) for f in report_definition['dimensions']],
metrics=[Metric(name=f['expression']) for f in report_definition['metrics']],
date_ranges=[DateRange(start_date=date, end_date=date)],
)
response = client.run_report(request)
And the client is BetaAnalyticsDataClient as also mentioned in the documentation:
credentials = Credentials(
token=None,
refresh_token=config['refresh_token'],
client_id=config['client_id'],
client_secret=config['client_secret'],
token_uri="https://accounts.google.com/o/oauth2/token",
scopes=["https://www.googleapis.com/auth/analytics.readonly"]
)
client = BetaAnalyticsDataClient(credentials=credentials)
It is not a Service Account so I am using google.oauth2.credentials.Credentials class as same in other Google APIs.
However, this operation is throwing an exception during the run_report function:
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNAVAILABLE
details = "Getting metadata from plugin failed with error: ('invalid_grant: Bad Request', {'error': 'invalid_grant', 'error_description': 'Bad Request'})"
debug_error_string = "UNKNOWN:Error received from peer analyticsdata.googleapis.com:443 {created_time:"2023-01-14T14:12:10.907813+03:00", grpc_status:14, grpc_message:"Getting metadata from plugin failed with error: (\'invalid_grant: Bad Request\', {\'error\': \'invalid_grant\', \'error_description\': \'Bad Request\'})"}"
>
And when I try to use my access token in the credentials:
credentials = Credentials(
token=config["token"],
refresh_token=config['refresh_token'],
client_id=config['client_id'],
client_secret=config['client_secret'],
token_uri="https://accounts.google.com/o/oauth2/token",
scopes=["https://www.googleapis.com/auth/analytics.readonly"]
)
This time I am getting following error:
google.api_core.exceptions.Unauthenticated: 401 Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
I am sure that my credentials is correct since I am using same account in my other repos.
Also, note that, I tried same operation with a service account and it does not give any error. However, for this purpose, I need to use a regular developer account since the OAuth flow is on a frontend project.
What are the suggestions on that issue? Is it possible to use a developer account in here and if yes, how?
I was able to fix the issue. The app just needs a sign-out sign-in (or refreshing the access token).

How to use the resource_owner grant within Microsoft365R

I'm trying to implement an unattended script accessing files within OneDrive using Microsoft365R.
I've setup everything like in the docs using the default app registration.
The interactive flow with auth_type="device_code" works without issues:
odb <- Microsoft365R::get_business_onedrive(auth_type="device_code")
But when trying auth_type="resource_owner" like shown in the docs here, I get the following error:
odb <- Microsoft365R::get_business_onedrive(tenant=tenant, app=app, username=user, password=getPass(), auth_type="resource_owner")
Error in process_aad_response(res) :
Bad Request (HTTP 400). Failed to obtain Azure Active Directory token. Message:
AADSTS50126: Error validating credentials due to invalid username or password.
My guess is, that the default app is missing some privileges to use the "resource_owner" flow.
Can someone point me to the right direction on how to get the resource_owner flow working?
(Using Service Principles is not a solution for my setup, but I did also try it with a dedicated service account and it was not working either)

How to fix "invalid return_url" error when creating oauth token for Trello with httr?

I want to manage my Trello cards and boards using the trelloR package but when I try to create a token with the get_token function, I get an error message on my browser : "Invalid return_url".
my_token <- get_token(key = my_key, secret = my_secret)
my_key is my personal Trello API key and my_secret is my OAuth secret. I got them on the Trello page that gives you your authentication codes, after login : https://trello.com/app-key
To use the Trello API and to access to boards, I need a token. This token is generated with OAuth1.0 by the httr package. Indeed, the function get_token do something like this, according to Jakub Chromec, author and maintainer of trelloR here :
trello.app = httr::oauth_app(
appname = "trello-app",
key = my_key,
secret = my_secret)
trello.urls = httr::oauth_endpoint(
request = "OAuthGetRequestToken",
authorize ="OAuthAuthorizeToken?scope=read&expiration=30days&name=trello-app",
access = "OAuthGetAccessToken",
base_url = "https://trello.com/1")
httr::oauth1.0_token(
endpoint = trello.urls,
app = trello.app)
When I execute this code or the function get_token with my personal key and secret, I am redirected to my browser, which is normal. As described on this page, a screen should appear asking me to allow authentication. But instead I just have an error message in the browser : "Invalid return_url".
In the RStudio console, this remains displayed :
> my_token <- get_token(my_key, my_secret)
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
I'm using httr 1.4.1, curl 4.2 and trelloR 0.6.0 with R 3.6.1 under macOS 10.15.
Some people reported the problem started after the introduction of Allowed Origins and they were able to fix it by adding the following origin:
http://localhost:1410
on the appkey page. This is a bit surprising to me as the default * should cover all origins, but there you go.
Trying this today (11/23/2019), I could not get wildcards to work as Allowed Origins. You should specify the domain of where you are running the call for authorization.
One source of confusion: The comments under "Allowed Origins" on https://trello.com/app-key refer to sites that "your application is allowed to redirect back to following the authorization flow." That was a bit confusing to me. The list should include sites you want to redirect back to IN ADDITION TO the sites you are calling Trello.authorize() from.
If you are thinking "I don't need a redirect" (and, in fact, if you are using client.js, I don't think you can specify a redirect), then those comments under "Allowed Origins" could lead you to believe you don't need to specify anything there. That would be incorrect.
Summary: Even if you want NO post-authorization re-direct, you still have to list an ORIGIN.
Also, you cannot specify file:// in Allowed Origins, so you cannot run your javascript off a local file.

RMonkey: Can't integrate survey data from SurveyMonkey to R, can't get OAuth 2.0

I want to connect the survey responses from my SurveyMonkey survey to R so that these can be analysed in real time as they come in for an RShiny dashboard.
I've loaded the Rmonkey package, and I've created a private app through SurveyMonkey and derived the SurveyMonkey username, password, client ID, SurveyMonkey secret, access token and the OAuth Redirect URL. Below is my code
options(sm_api_key = 'xxxxx')
options(sm_secret = 'yyyy')
options(sm_client_id = 'zzzz')
smlogin()
After running that, we are directed to a web browser and get the following error message: "Survey Monkey The authorization request failed: API key is not required for this app."
We have been using this document for help (https://github.com/cloudyr/Rmonkey) but are concerned that it is from 2016 and thus may be outdated. Any help would be appreciated. Thanks in advance!

Resources