Google Api Php Client - Google Auth OAuth 2 - google-oauth

My code:
if ($client->getAccessToken()) {
$_SESSION['access_token'] = $client->getAccessToken();
$obj_token = json_decode($client->getAccessToken());
$accessToken = $obj_token->access_token;
$token_data = $client->verifyIdToken($accessToken)->getAttributes();
}
Error:
Uncaught exception 'Google_Auth_Exception' with message 'Wrong number of segments in token: ya29.qQH27NhAXVXPJ64txBjhT_j1FNaVCjosyfwUFKpgsn9LBiyNDS7wgDXVDR31y9hvFbM824mrzOcrWA'
$accessToken should be a string with 2 "." but i don't know why $token_data return a29.qQH27NhAXVXPJ64txBjhT_j1FNaVCjosyfwUFKpgsn9LBiyNDS7wgDXVDR31y9hvFbM824mrzOcrWA', that only have 1 "."

You're trying to verify an access_token as an id_token. They are different tokens, serving different purposes. For an id_token example see the code at https://github.com/google/google-api-php-client/blob/master/examples/idtoken.php, so:
$token_data = $client->verifyIdToken()->getAttributes();
assuming that an id_token was returned by Google as part of the handshake in the first place.

Related

Azure Data Factory web activity to retrieve bearer token

I want to invoke an api that returns bearer token (GET method). I can fetch Bearer Token successfully using .Net code. But with ADF I get only 'OK' and I see no option to fetch the Bearer Token.
Example:
ApiUrl = "https://myapi.mysite.org/api/ApiToken?user=u111&password=p111"
if status code = 'OK' then deserialize result content to fetch toekn.
Sample .Net code I used to fetch Bearer Token successfully:
var result = client.PostAsync(ApiUrl).Result;
string strRes = result.StatusCode.ToString();
if (strRes == "OK")
{
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject(result.Content.ReadAsStringAsync().Result);
varToken = obj.Token;
}
Use POST method in Azure data factory web activity to get the access token from an API.
Add header as content-Type: application/x-www-form-urlencoded and pass the access credentials in the body part.
You can refer to this link1 & link2 for working examples.

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"}

Getting A Refresh Token From Google Using An Authorization Token Posted in Java

I have read many posts, all the Google documentation I can find and tried many iterations of the following and still can't get an access and refresh token. I do get an authorization code but can't seem to get that to trade for the access and refresh tokens.
if(authCode == null || authCode.equals("")) {
String url = "https://accounts.google.com/o/oauth2/v2/auth?"
+ "scope=https://mail.google.com/&"
+ "response_type=code&"
+ "redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&"
+ "client_id=" + clientId +
"&access_type=offline";
URI uri = new URI(url);
logger.debug("URI for auth is: " + uri);
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(uri);
}
}
else {
logger.debug("Refreshing");
initRefreshToken();
}
With that, I get an access code I can cut and paste (just testing and trying to get this to work first) in my properties to get the refresh and access token.
In the initRefreshToken() method, the source is like this:
if(refreshToken.equals("")) {
logger.debug("Getting refresh token");
HttpPost post = new HttpPost("https://oauth2.googleapis.com/token");
// add request parameter, form parameters
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("code", authCode));
urlParameters.add(new BasicNameValuePair("client_id", clientId));
urlParameters.add(new BasicNameValuePair("client_secret", clientSecret));
urlParameters.add(new BasicNameValuePair("redirect_uri", "http://localhost:8000/"));
urlParameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
try {
post.setEntity(new UrlEncodedFormEntity(urlParameters));
System.out.println("***** URL: " + urlParameters);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post);
System.out.println(EntityUtils.toString(response.getEntity()));
}
If this is a second or subsequent time using the code, what will be printed is:
Refersh token:
***** URL: [code=4/1AY0e-g..., client_id=370...i1h2u1s.apps.googleusercontent.com, client_secret=bAOH..., redirect_uri=https://localhost:8000/, grant_type=authorization_code]
{
"error": "invalid_grant",
"error_description": "Bad Request"
}
If the code is run and it's the first time using an authentication code, it will print:
{
"error": "redirect_uri_mismatch",
"error_description": "Bad Request"
}
I read in the Google console that exceptions are made for localhost domains so there's no need to register them. However, if there were a need to register them, it won't let you register them anyway as a domain must be a top level domain you own in order to register it. Therefore, how do I register localhost and/or exchange an authorization code for an access and refresh token in Java?
Thank you for your help.
DaImTo provided a great video about this and in that video and the blog post associated with it, the redirect_uri is listed correctly as: "urn:ietf:wg:oauth:2.0:oob". I didn't find this in the documentation but when I added it to my source code, I got access and refresh tokens as a response. Thank you very much for that help, DaImTo.

How to fix "The OAuth client was not found" error from a Bing Ads script

We've got scripts on Bing to automatically adjust ad bids based on ad performance and client goals, which are stored in a Google spreadsheet.
We had a contractor set this up initially, and it worked. But I guess that the contractor was using a temp Google account and when it went away the bidders stopped working. Because it did work before, it's likely a configuration error on my part that's breaking it now, but the contractor pointed us to the steps I was already following to no avail (https://learn.microsoft.com/en-us/advertising/scripts/examples/authenticating-with-google-services#option2).
Stuff already tried
double checked for errant whitespace around the client ID and client secret
created new client secrets
created new client IDs
made sure that the project name, application name, and OAuth client id name were all the same
created whole new projects from scratch (configured to match the article cited above) to see if that would kick something loose
tried a different token URL (https://oauth2.googleapis.com/token) that appears in the client_secret JSON downloaded from Google
function main() {
const credentials = {
accessToken: '',
client_id: 'REDACTED.apps.googleusercontent.com', // from Google developer console
client_secret: 'REDACTED', // from Google developer console
refresh_token: 'REDACTED' // created at https://developers.google.com/oauthplayground
};
var access_token = '';
if (credentials.accessToken) {
access_token = credentials.accessToken;
}
var tokenResponse = UrlFetchApp.fetch('https://www.googleapis.com/oauth2/v4/token', { method: 'post', contentType: 'application/x-www-form-urlencoded', muteHttpExceptions: true, payload: { client_id: credentials.clientId, client_secret: credentials.clientSecret, refresh_token: credentials.refreshToken, grant_type: 'refresh_token' } });
var responseCode = tokenResponse.getResponseCode();
var responseText = tokenResponse.getContentText();
if (responseCode >= 200 && responseCode <= 299) {
access_token = JSON.parse(responseText)['access_token'];
}
throw responseText;
// use the access token to get client targets from the spreadsheet
A JSON encoded access token is the expected response, but instead, we get HTTP 400 with the message "The OAuth client was not found."
Manually creating an access token on the OAuth playground (https://developers.google.com/oauthplayground) works as a stopgap, but this should work. This has worked. :P
The fix in this case switching the Application Type on console.developers.google.com > Credentials > OAuth consent screen to Internal instead of Public.
That wasn't in the steps provided by Microsoft, and I'm not sure if that will have implications down the road, but at least we're off the manual process for now.

Monzo API: Invalid request: required parameter client_id is unknown

I keep getting the following error Invalid request: required parameter client_id is unknown when making a request to the monzo auth api to get an access token. I am getting the client_id from the developer playground response using GET /ping/whoami.
I am then putting this into my request:
let clientID = "oauthclient_XXXXXXXXXXXXXXXX"
let baseURL = "https://auth.monzo.com/"
let redirectURI = "https://Monzo-AR.novoda.com"
let responseType = "code"
let stateToken = "random string"
var requestURL: String!
requestURL = baseURL +
"?client_id=" +
clientID +
"&redirect_uri=" +
redirectURI +
"&response_type=" +
responseType +
"&state=" +
stateToken
Can anyone see what i am doing wrong?
The /ping/whoami endpoint returns the client_id for the Developer Console (which was used to authenticate you for that service)
It's not suggested to use that client_id in your own applications. If you head to the Monzo Clients Page you will be able to create your own client and receive an ID for it.
Additionally, the redirect URI must match that of the one configured in the clients page linked before (You will get an error otherwise)
You haven't given context to what you're doing with the requestURL - You will need to redirect the user to this page in order to authenticate.
Once you have been redirected to the authentication page at the link you've constructed, you'll be able to use your browsers console (Cmd + Option + J on Chrome Mac) to see any errors that present themselves