Downloading Secondary Domain User Documents Google Document List Api 2-Legged Oauth - google-drive-api

First post so sorry for any formatting issues.
I am trying to download a secondary domain user's documents via oauth and receiving a com.google.gdata.util.AuthenticationException: Unauthorized error. I am able to pull the users document using a feed call similar to this :
String docUrl = "https://docs.google.com/feeds/" + DOC_OWNER + "/private/full/" + DOC_ID + "?xoauth_requestor_id="+ PRIMARY_ADMIN_EMAIL
DocumentListEntry googleDoc = docServ.getEntry(new URL(docUrl), DocumentListEntry.class);
String exportUrl = ((MediaContent) googleDoc.getContent()).getUri().toString();
exportString = ((MediaContent) googleDoc.getContent()).getUri().split("&xoauth_requestor_id=")[0];
exportString + EXPORT_TYPE // add export type
but then when trying to download the document such as :
MediaContent mc = new MediaContent();
mc.setUri(exportUrl);
String mcUrl = mc.getUri() + "&xoauth_requestor_id=" + DOC_OWNER;
MediaSource ms = docServ.getMedia(mc);
This throws the authentication exception. I have tried swapping out the requestor id for the primary domain admin with no success. I have also tried using user creds for the primary domain admin and that throws a service forbidden exception. Anyone have any suggestions?

By default, the domain's OAuth key/secret don't have access to secondary domains. You need to manually enter the key (primary domain) and the Docs API scopes:
https://docs.google.com/feeds/,https://docs.googleusercontent.com/,https://spreadsheets.google.com/feeds/
at:
https://www.google.com/a/cpanel/YOUR-DOMAIN-HERE/ManageOauthClients
for it to work with secondary domain accounts.

Related

LoginRadius Validating access token .net core

I am trying to validate my access token (not JWT) with LoginRadius, I can do the login but after when I call my API I always get unauthorized or different errors according to my Authentication configuration, I am using like this. I believe the authority url is not correct but I couldn't find any other
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect("login-radius", options => {
// Set the authority to your Auth0 domain
options.Authority = $"https://api.loginradius.com/identity/v2/auth/";
// Configure the Auth0 Client ID and Client Secret
options.ClientId = Configuration["ClientId"];
options.ClientSecret = Configuration["ClientSecret"];
// Set response type to code
options.ResponseType = OpenIdConnectResponseType.Code;
options.Scope.Clear();
options.Scope.Add("openid");
options.CallbackPath = new PathString("/callback");
options.ClaimsIssuer = "loginradius";
// Saves tokens to the AuthenticationProperties
options.SaveTokens = true;
});
I believe you are trying to setup OIDC, and to configure it, please refer to the LoginRadius docs on OIDC, as it needs few things that need to be configured in the Admin Console and the correct authority URL: https://www.loginradius.com/docs/single-sign-on/tutorial/federated-sso/openid-connect/openid-connect-overview/#otheropenidfunctionality6
Please refer to the OIDC discovery endpoint, which provides a client with configuration details about the OpenID Connect metadata of the Loginradius App.
URL Format: https://cloud-api.loginradius.com/sso/oidc/v2/{sitename}/{oidcappname}/.well-known/openid-configuration
My account didn't have access to few features

Google apps script for Gmail - broken email from inbox [duplicate]

This question already has an answer here:
Gmail AppScript mailMessage.getFrom() to return email not name
(1 answer)
Closed 2 years ago.
I have developed a Gmail add-on.
In that I will get the list of emails in from, to, cc and bcc with the help of GmailMessage class.
like for from email , GmailMessage.getFrom()
for to email, GmailMessage.getTo()
In the documentation it is stated that it will return an email as string but it is not clearly mentioned anywhere about the format of that string.
Sometimes I'm getting in the format of Name of the account<accountEmail#gmail.com>
and sometimes in the format of <accountEmail#gmail.com> and sometimes only name will be available without the email ID of the recepient.
Sometimes it also includes double quotes on the email like Name of the account<"accountEmail#gmail.com">
Can someone tell is there a way to get the exact email address and name separately from Gmail using Google apps script?
Or suggest some ways to parse the email from GmailMessage class and get email address and name separately
I found the the gmail api site (here) which might come in use if you end up using the code. Although the code is in python so it might not work on google app script, but the only reason to use google apps script is to achieve these results. You also are going to have to know what you are doing when using this(if you want to use google app script, try making a gmail app template then go here to learn the basics (here) and here for further documentation (here))
Replace CLIENTSECRETS_LOCATION value with the location of your client_secrets.json file.
import logging
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
from apiclient.discovery import build
# ...
# Path to client_secrets.json which should contain a JSON document such as:
# {
# "web": {
# "client_id": "[[YOUR_CLIENT_ID]]",
# "client_secret": "[[YOUR_CLIENT_SECRET]]",
# "redirect_uris": [],
# "auth_uri": "https://accounts.google.com/o/oauth2/auth",
# "token_uri": "https://accounts.google.com/o/oauth2/token"
# }
# }
CLIENTSECRETS_LOCATION = '<PATH/TO/CLIENT_SECRETS.JSON>'
REDIRECT_URI = '<YOUR_REGISTERED_REDIRECT_URI>'
SCOPES = [
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
# Add other requested scopes.
]
class GetCredentialsException(Exception):
"""Error raised when an error occurred while retrieving credentials.
Attributes:
authorization_url: Authorization URL to redirect the user to in order to
request offline access.
"""
def __init__(self, authorization_url):
"""Construct a GetCredentialsException."""
self.authorization_url = authorization_url
class CodeExchangeException(GetCredentialsException):
"""Error raised when a code exchange has failed."""
class NoRefreshTokenException(GetCredentialsException):
"""Error raised when no refresh token has been found."""
class NoUserIdException(Exception):
"""Error raised when no user ID could be retrieved."""
def get_stored_credentials(user_id):
"""Retrieved stored credentials for the provided user ID.
Args:
user_id: User's ID.
Returns:
Stored oauth2client.client.OAuth2Credentials if found, None otherwise.
Raises:
NotImplemented: This function has not been implemented.
"""
# TODO: Implement this function to work with your database.
# To instantiate an OAuth2Credentials instance from a Json
# representation, use the oauth2client.client.Credentials.new_from_json
# class method.
raise NotImplementedError()
def store_credentials(user_id, credentials):
"""Store OAuth 2.0 credentials in the application's database.
This function stores the provided OAuth 2.0 credentials using the user ID as
key.
Args:
user_id: User's ID.
credentials: OAuth 2.0 credentials to store.
Raises:
NotImplemented: This function has not been implemented.
"""
# TODO: Implement this function to work with your database.
# To retrieve a Json representation of the credentials instance, call the
# credentials.to_json() method.
raise NotImplementedError()
def exchange_code(authorization_code):
"""Exchange an authorization code for OAuth 2.0 credentials.
Args:
authorization_code: Authorization code to exchange for OAuth 2.0
credentials.
Returns:
oauth2client.client.OAuth2Credentials instance.
Raises:
CodeExchangeException: an error occurred.
"""
flow = flow_from_clientsecrets(CLIENTSECRETS_LOCATION, ' '.join(SCOPES))
flow.redirect_uri = REDIRECT_URI
try:
credentials = flow.step2_exchange(authorization_code)
return credentials
except FlowExchangeError, error:
logging.error('An error occurred: %s', error)
raise CodeExchangeException(None)
def get_user_info(credentials):
"""Send a request to the UserInfo API to retrieve the user's information.
Args:
credentials: oauth2client.client.OAuth2Credentials instance to authorize the
request.
Returns:
User information as a dict.
"""
user_info_service = build(
serviceName='oauth2', version='v2',
http=credentials.authorize(httplib2.Http()))
user_info = None
try:
user_info = user_info_service.userinfo().get().execute()
except errors.HttpError, e:
logging.error('An error occurred: %s', e)
if user_info and user_info.get('id'):
return user_info
else:
raise NoUserIdException()
def get_authorization_url(email_address, state):
"""Retrieve the authorization URL.
Args:
email_address: User's e-mail address.
state: State for the authorization URL.
Returns:
Authorization URL to redirect the user to.
"""
flow = flow_from_clientsecrets(CLIENTSECRETS_LOCATION, ' '.join(SCOPES))
flow.params['access_type'] = 'offline'
flow.params['approval_prompt'] = 'force'
flow.params['user_id'] = email_address
flow.params['state'] = state
return flow.step1_get_authorize_url(REDIRECT_URI)
def get_credentials(authorization_code, state):
"""Retrieve credentials using the provided authorization code.
This function exchanges the authorization code for an access token and queries
the UserInfo API to retrieve the user's e-mail address.
If a refresh token has been retrieved along with an access token, it is stored
in the application database using the user's e-mail address as key.
If no refresh token has been retrieved, the function checks in the application
database for one and returns it if found or raises a NoRefreshTokenException
with the authorization URL to redirect the user to.
Args:
authorization_code: Authorization code to use to retrieve an access token.
state: State to set to the authorization URL in case of error.
Returns:
oauth2client.client.OAuth2Credentials instance containing an access and
refresh token.
Raises:
CodeExchangeError: Could not exchange the authorization code.
NoRefreshTokenException: No refresh token could be retrieved from the
available sources.
"""
email_address = ''
try:
credentials = exchange_code(authorization_code)
user_info = get_user_info(credentials)
email_address = user_info.get('email')
user_id = user_info.get('id')
if credentials.refresh_token is not None:
store_credentials(user_id, credentials)
return credentials
else:
credentials = get_stored_credentials(user_id)
if credentials and credentials.refresh_token is not None:
return credentials
except CodeExchangeException, error:
logging.error('An error occurred during code exchange.')
# Drive apps should try to retrieve the user and credentials for the current
# session.
# If none is available, redirect the user to the authorization URL.
error.authorization_url = get_authorization_url(email_address, state)
raise error
except NoUserIdException:
logging.error('No user ID could be retrieved.')
# No refresh token has been retrieved.
authorization_url = get_authorization_url(email_address, state)
raise NoRefreshTokenException(authorization_url)

How to integrate Zoho CRM with Messagebird

I am trying to authenticate to messagebird using a custom function of zoho CRM. I am trying the following script:
//HEADER
API_Key = "***"; I am hiding the API Key
HeaderMap = Map();
HeaderMap.put("Content-Type","application/json");
HeaderMap.put("Authorization","Access Key " + API_Key);
ENDPOINT = "https://conversations.messagebird.com/v1/send";
Request = invokeurl
[
url :ENDPOINT
type :POST
headers:HeaderMap
];
I am getting this error:
{"errors":[{"code":2,"description":"Request was not authenticated"}]}
and i am passing this json:
{"Content-Type":"application/json","Authorization":"Access Key ***"}
Does any one if i am doing something wrong?
AccessKey should be in one word
HeaderMap.put("Authorization","AccessKey" + API_Key);
Extract from my FlowBuilder example:
worth noting that the webhook related APIs only work with LIVE API keys. I didn't see any mention of that anywhere in the docs, but it only worked for me after trying with a live key... I hope this will save someone some time!

Apache HTTP Client Fluent

Hi I want to use Apache HTTP Client Fluent to create a request to download a file. I need to add Autorization Basic Auth to the request to pass in a username and password which I can't find a good example of how to do.
I can see a addHeader method but can't find good examples of how to construct it. Thanks!
So far the code i have is:
String auth = username + ":"+ token
byte[] encodedBytes = Base64.encodeBase64(auth.getBytes());
String encodedAuth = new String(encodedBytes)
URL downloadFileURL = new URL (urlbuild)
Executor executor = Executor.newInstance();
executor.execute(Request.Get(downloadFileURL.toURI())
.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth )
.connectTimeout(1000))
.saveContent(new File(mobileAppPath + System.getProperty("file.separator") + mobileApp.name));
the problem was due to Java trying to validate the SSL certificate i used Java code below to trust all hosts before executing the request.
https://www.javatips.net/api/java.security.cert.x509certificate

How to pull data from Toggl API with Power Query?

First timer when it comes to connecting to API. I'm trying to pull data from Toggl using my API token but I can't get credentials working. I tried to replicate the method by Chris Webb (https://blog.crossjoin.co.uk/2014/03/26/working-with-web-services-in-power-query/) but I can't get it working. Here's my M code:
let
Source = Web.Contents(
"https://toggl.com/reports/api/v2/details?workspace_id=xxxxx&client=xxxxxx6&billable=yes&user_agent=xxxxxxx",
[
Query=[ #"filter"="", #"orderBy"=""],
ApiKeyName="api-token"
])
in
Source
After that I'm inputting my API Token into Web API method in Access Web content windows but I get an error that credentials could not be authenticated. Here's Toggl API specification:
https://github.com/toggl/toggl_api_docs/blob/master/reports.md
Web.Contents function receives two parameters: url + options
Inside options, you define the headers and the api_key, and other queryable properties, such as:
let
baseUrl = "https://toggl.com/",
// the token part can vary depending on the requisites of the API
accessToken = "Bearer" & "insert api token here"
options = [
Headers = [Authorization = accessToken, #"Content-Type" =
"application/Json"], RelativePath ="reports/api/v2/details", Query =
[workspace_id=xxxxx, client=xxxxxx6 , billable=yes, user_agent=xxxxxxx]
]
Source = Web.Contents(baseUrl, options)
// since Web.Contents() doesn't parse the binaries it fetches, you must use another
// function to see if the data was retreived, based on the datatype of the data
parsedData = Json.Document(Source)
in
parsedData
The baseUrl is the smallest url that works and never changes;
The RelativePath is the next part of the url before the first "?".
The Query record is where you define all the attributes to query as a record.
This is usually the format, but check the documentation of the API you're querying to see if it is similar.