How to set callback URL for Google OAuth? - oauth

I am using Google OAuth to authenticate the user in my GAE application. After the user clicks on "Grant Access", I want to return to my application. I tried setting the callback URL, but instead of being called independently, it gets appended to the current URL in the browser, and thus shows as an invalid URL.
Here is my code:
OAuthGetTemporaryToken requestToken = new OAuthGetTemporaryToken(REQUEST_TOKEN_URL);
requestToken.consumerKey = CONSUMER_KEY;
requestToken.transport = TRANSPORT;
requestToken.signer = signer;
requestToken.callback="www.mail.yahoo.com";
OAuthCredentialsResponse requestTokenResponse = requestToken.execute();
// updates signer's token shared secret
signer.tokenSharedSecret = requestTokenResponse.tokenSecret;
OAuthAuthorizeTemporaryTokenUrl authorizeUrl = new OAuthAuthorizeTemporaryTokenUrl(AUTHORIZE_URL);
authorizeUrl.temporaryToken = requestTokenResponse.token;
This line sends it to the Google OAuth page.
resp.sendRedirect(authorizeUrl.build());
I have set the callback parameter as shown above, but it's not working. Please help! Thanks in advance.

This is OAuth1 stuff, which is deprecated. Try using OAuth 2.0 instead. Start at https://developers.google.com/accounts/docs/OAuth2

Related

Call Graph API from MVC App

SUMMARY UPDATE:
I got a sample working today thanks to the many good replies. Thanks all. My primary goal was to get current user information (ME) without using secret key. First I just used the secret key from the App Reg and this will authenticate the App and not the user. This does of course not work when calling ME. My next finding was if you want the users token, you still need the App Reg token, and then you request the users token. This requires less permissions on the App Reg, but requires to request two tokens. I ended up skipping ME and just requesting information for a specified user (through the APp Reg permissions):
$"https://graph.microsoft.com/v1.0/users/{email}/$select=companyName"
Both both approaches should be viable. I updated code below with working sample.
I am trying to do a very simple call to graph API to get companyName from current user. Found some samples but they seemed to be very complicated. The MVC app is authenticated trough an Application Registration in AAD.
I guess the application registration needs to be authorized to access Graph API. Or is more needed here? Getting company name should be fairly simple:
https://graph.microsoft.com/v1.0/me?$select=companyName
Does anyone have a snippet for calling the graph API, my best bet would be you need to extract a bearer token from the controller? ALl help is appreciated.
Working snippet:
public async Task<ActionResult> Index()
{
string clientId = "xxx";
string clientSecret = "xxx";
var email = User.Identity.Name;
AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/xxx.onmicrosoft.com/oauth2/token");
ClientCredential creds = new ClientCredential(clientId, clientSecret);
AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", creds);
HttpClient http = new HttpClient();
string url = $"https://graph.microsoft.com/v1.0/users/{email}/$select=companyName";
//url = "https://graph.windows.net/xxx.onmicrosoft.com/users?api-version=1.6";
// Append the access token for the Graph API to the Authorization header of the request by using the Bearer scheme.
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
HttpResponseMessage response = await http.SendAsync(request);
var json = response.Content.ReadAsStringAsync();
return View();
}
To add one last item, here is a link to an MVC sample on Git that uses an MVC application to send email. It illustrates how to call the MS Graph API to get various pieces of information. Keep in mind, if you are using an application only scenario, ME will not work, the sample illustrates how to obtain a delegated token for a user and use that toke to do work:
https://github.com/microsoftgraph/aspnet-connect-rest-sample
If I am reading this code snippet correctly, You are requesting a application only token for the Graph.Microsoft.Com resource, then attempting to use that toke with this URI:
url = "https://graph.windows.net/thomaseg.onmicrosoft.com/users?api-version=1.6"
This will not work because you are mixing resources, AAD Graph and MS Graph. The ME endpoint does not make since in this scenario because you are using the application only flow. This flow does not support the ME endpoint. ME is designed for use with a delegated token. the ME endpoint represents the signed in user, since and application is not a user, ME is meaningless.
You will need to target the user specifically:
https://graph.microsoft.com/v1.0/Users/[UPN or ID of user]?$select=companyName
Should work if your application has been granted the appropriate permission scopes.

Why is requesting for authorization of my Twitter app for a new user generating a PIN?

I've created a twitter app and I have all the credentials (access token, secret, consumer key and secret). I'm using Abraham's Twitter Oauth. I've been able to get the application running but I am currently unable to Authorize a new account successfully. Instead, it is requesting for a new user to input a PIN generated after the user has granted access, before the authorization is complete.
I've done some lookup on the internet and it pointed out to Twitter.com's manual here and here. From what I've been able to read up, Implementing a desktop sign in request requires oauth_callback value. I've tried to add a value to this parameter, but it returns an error: Fatal error: Uncaught exception 'Abraham\TwitterOAuth\TwitterOAuthException' with message '<?xml version="1.0" encoding="UTF-8"?> <hash> <error>Desktop applications only support the oauth_callback value 'oob'</error> <request>/oauth/request_token</request> </hash> ', but if I don't add a value to the oauth_callback parameter, it redirects to Twitter.com's authorization page successfully, but then, generates a PIN which will be required to be filled in the application.
I sincerely do not know how to go round this, any help will be much appreciated.
Here's my code below:
require_once "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
//Check if form was submitted
if(isset($_GET['activate-account']) && $_GET['activate-account'] == 'true'){
session_start();
//Get App Details (Consumer key and secret) from DB
$appID = 1;
$consumerKey = getAutoTweetPart($appID, 'consumer_key');
$consumerSecret = getAutoTweetPart($appID, 'consumer_secret');
$callBack = '';
$connection = new TwitterOAuth($consumerKey, $consumerSecret);
$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => $callBack));
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
$url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));
header('Location: '. $url);
}
You should check that your app (linked from https://apps.twitter.com) has a callback URL specified, so that you are not using desktop mode. The callback URL should not be locked unless it is always the same e.g. constant host/port.
Then your request_token call can specify the URL you want the user redirected to.
This is part of the flow described here https://dev.twitter.com/web/sign-in/implementing

google authentication expired token

I need to recover user info after javascript google login.
Authentication work fine and i send googleUser.Ka object to my php where there's this code
$api = new Google_Client();
$api->setApplicationName($this->_configCustomer['google']['api']['application_name']);
$api->setClientId($this->_configCustomer['google']['api']['client_id']); // Set Client ID
$api->setClientSecret($this->_configCustomer['google']['api']['client_secret']); //Set client Secret
$api->setAccessType('online'); // Access method
$api->setScopes(array('https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'));
//$api->setRedirectUri('http://www.infotuts.com/demo/googlelogin/login.php');
$service = new Google_Service_Plus($api);
$oauth2 = new \Google_Service_Oauth2($api);
$api->setAccessToken(json_encode($_POST));
//ADDED AFTER ERROR
if($api->isAccessTokenExpired()) {
$api->authenticate();
$NewAccessToken = json_decode($api->getAccessToken());
$api->refreshToken($NewAccessToken->refresh_token);
}
//END ADDED AFTER FIRST ERROR
//$api->authenticate($_POST['access_token']);
if ($api->getAccessToken()) {
$data = $service->people->get('me');
$user_data = $oauth2->userinfo->get();
var_dump($user_data);
die();
}
this code generate the error:
The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved.
i added code indicate from comment follow this link
OAuth 2.0 access token has expired, and a refresh token is not available
but in the last version of php authenticate method require $code parameter. What is it?
Thanks
i solved in this way
$api = new Google_Client();
$api->setApplicationName($this->_configCustomer['google']['api']['application_name']);
$api->setClientId($this->_configCustomer['google']['api']['client_id']); // Set Client ID
$api->setClientSecret($this->_configCustomer['google']['api']['client_secret']); //Set client Secret
$api->setAccessType('online'); // Access method
$api->setScopes(array('https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'));
$api->setRedirectUri('postmessage');
$result = $api->verifyIdToken($_POST['id_token']);
i send id_token, obtained from the ajax login, and recovery user info using verifyIdToken method of client library

Using Doubleclick Bid Manager API

I am writing a Python program to read line items from Doubleclick Bid Manager using its API, but facing issue while making a query to getlineitems.
To Authenticate, here is my code:
authorize_url = flow.step1_get_authorize_url()
# After entering the verification for code,
code = raw_input('Code: ').strip()
credential = flow.step2_exchange(code)
I successfully get my credential as a oauth2client.client.OAuth2Credentials object.
Then using following parameters, I make a http request.
params = dict(
api_key='xxxxxxxxxxxxxxxxxx' # client secret from the API JSON file
)
url = 'https://developers.google.com/bid-manager/v1/lineitems/downloadlineitems'
r = requests.get(url = url, params=params)
But my request returns 404; not found code. Per the API guidelines (https://developers.google.com/bid-manager/v1/lineitems/downloadlineitems), you need to make following HTTP request.
POST https://www.googleapis.com/doubleclickbidmanager/v1/lineitems/downloadlineitems?key={YOUR_API_KEY}
Any help will be appreciated.
I don't know much about python, but since the call is a POST request, should you be using requests.get()? Is there a request.post() method?

slack api rtm.start missing_scope needed client

I have get access token and when I try to post rtm.start, I am getting below error:
{
error = "missing_scope";
needed = client;
ok = 0;
provided = "identify,read,post";
}
I have set the scope to read,post,identify in authorize API. I have read the API document over and over again. Only rtm.start mentioned client scope. But in oauth document I didn't find a client scope. So, what's wrong?
You have to do it before you get the token.
when you do the initial request to connect the app, include &scope="identify,read,post,client"
Under App Credentials get your Client ID and Client Secret.
Goto:
https://#{team}.slack.com/oauth/authorize?client_id=#{cid}&scope=client
replacing #{team} and #{cid} with your values.
When you approve the authorization you’ll goto that real url that doesn’t resolve. Copy the whole url to your clipboard and paste it into a text file. Extract out just the “code” part.
Now goto:
https://#{team}.slack.com/api/oauth.access?client_id=#{cid}&client_secret=#{cs}&code=#{code}"
And you’ll get back a token like:
xoxp-4422442222–3111111111–11111111118–11aeea211e
(from here: https://medium.com/#andrewarrow/how-to-get-slack-api-tokens-with-client-scope-e311856ebe9)

Resources