scribe oauth linkedin creat token - grails

I am trying to use the scribe oAuth plugin (in a grails environment). I am able to get the user to authorize my app and authenticate. I can then get the xml response. my question, though, is how do I re-query a users profile without having to have them re-authorize my app. Once they authorize it the first time, I capture their Token and Secret key. So, shouldn't I be able to re-query the profile (as long as they do not revoke their authorization.)? I was able to do this with the older version of the plugin. The problem is with creating a new token. I don't see a way to create the Authorization token without the Verifier and Request Token (which wont exist because my code is executing the query on their behalf, with their permission.)
If I try to create the token like this:
Token accessToken = new Token()
accessToken.secret="XXX"
accessToken.token = "YYY"
I get an initialization error.
I can't create it like this, because I dont have the Request token and verifier:
Token accessToken = service.getAccessToken(requestToken, verifier);
accessTokenSecret = accessToken.secret
accessTokenKey = accessToken.token
And If i dont have the access token object, I am unable to sign my request. The full code looks like this (assuming their is a request token and verifier)
OAuthService service=new ServiceBuilder()
.provider(LinkedInApi.class)
.apiKey(apiKey)
.apiSecret(apiSecret)
.build();
Verifier v = new Verifier(ver);
Token accessToken = service.getAccessToken(rt, v);
accessTokenSecret = accessToken.secret
accessTokenKey = accessToken.token
OAuthRequest request = new OAuthRequest(Verb.GET, apiUrl);
service.signRequest(accessToken, request);
Response response = request.send();
xmlString=response.getBody();
Thanks for your help
jason

well, after some time, I got this to work:
public getProfileWithTokens(getAccessToken, getAccessTokenSecret){
Token newAccessToken = new Token(getAccessToken, getAccessTokenSecret);
String xmlString =""
OAuthService service=new ServiceBuilder()
.provider(LinkedInApi.class)
.apiKey(apiKey)
.apiSecret(apiSecret)
.build();
OAuthRequest request = new OAuthRequest(Verb.GET, apiUrl);
service.signRequest(newAccessToken, request);
Response response = request.send();
xmlString=response.getBody();
}

Related

OAuth1 Authentication in RestSharp for Twitter API GET and POST methods

Using Postman I'm successfully able to query and create tailored audiences using the Twitter API, using Postman's OAuth 1.0 Authorization. However when trying to do the same with RestSharp I get an Unauthorized error.
"UNAUTHORIZED_ACCESS" - "This request is not properly authenticated".
My GET request authenticates fine, but the POST request fails.
_twitterRestClient = new RestClient("https://ads-api.twitter.com/1")
{
Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, AccessToken, AccessSecret)
};
var restRequest1 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences", TwitterAccountId), Method.GET);
//this works and gives me a list of my tailored audiences
var response1 = _twitterRestClient.Execute(restRequest1);
var restRequest2 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences?name=SampleAudience2&list_type=EMAIL", TwitterAccountId), Method.POST);
// this results in an "Unauthorized" status code , and the message {\"code\":\"UNAUTHORIZED_ACCESS\",\"message\":\"This request is not properly authenticated\"}
var response2 = _twitterRestClient.Execute(restRequest2);
Turns out this is due to a quirk in RestSharp OAuth1 implementation. I think its related to this issue - https://www.bountysource.com/issues/30416961-oauth1-not-specifing-parameter-type . Part of creating an OAuth1 signature involves gathering all the parameters in the request and other details and then hashing it all. It looks like when the HTTP Method is a POST, then RestSharp is not expecting parameters in the querystring (which makes sense), its expecting them in the post body. Anyhow if you add parameters explicitly then they are picked up and the OAuth1 signing works. (Turns out the twitter API works if these params are in the post body, so I didn't need to explicitly add them to the query string). Updated code that now works:
_twitterRestClient = new RestClient("https://ads-api.twitter.com/1")
{
Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, AccessToken, AccessSecret)
};
var restRequest1 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences", TwitterAccountId), Method.GET);
var response1 = _twitterRestClient.Execute(restRequest1);
var restRequest2 = new RestRequest(string.Format("/accounts/{0}/tailored_audiences", TwitterAccountId), Method.POST);
restRequest2.AddParameter("name", "SampleAudience2");
restRequest2.AddParameter("list_type", "EMAIL");
var response2 = _twitterRestClient.Execute(restRequest2);

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

MVC 5 Identity 2 and Web API 2 authorization and call api using bearer token

The following scenario: I have an MVC 5 web app using Identity 2.0 and Web API 2.
Once the user authenticates in MVC 5 he should be able to call a WEB API endpoint let's call it: api/getmydetails using a bearer token.
What I need to know is how can I issue the token for that specific user in MVC 5?
I did solve this.
Here are some screenshots and I will also post the demo solution.
Just a simple mvc 5 with web api support application.
The main thing you have to register and after login. For this demo purpose I registered as admin#domain.com with password Password123*.
If you are not logged in you will not get the token. But once you loggin you will see the token:
After you get the token start Fiddler.
Make a get request to the api/service endpoint. You will get 401 Unauthorized
Here is the description of the request:
Now go to the web app, stage 1 and copy the generated token and add the following Authorization header: Authorization: Bearer token_here please notice the Bearer keyword should be before the token as in the image bellow. Make a new request now:
Now you will get a 200 Ok response. The response is actually the user id and user name that show's you are authorized as that specific user:
You can download the working solution from here:
http://www.filedropper.com/bearertoken
If for some reason the link doesn't work just let me know and I will send it to you.
P.S.
Of course in your app, you can use the generated bearer token to make ajax call to the web api endpoint and get the data, I didn't do that but should be quite easy ...
P.S. 2: To generate the token:
private string GetToken(ApplicationUser userIdentity)
{
if (userIdentity == null)
{
return "no token";
}
if (userIdentity != null)
{
ClaimsIdentity identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, userIdentity.UserName));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userIdentity.Id));
AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
DateTime currentUtc = DateTime.UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
string AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
return AccessToken;
}
return "no token";
}

how to get user information from Withings api on grails

I'm trying to get user information from Withings Api, i've already success login into Withings with Oauth using Scribe library(Java). But there is a problem when i sent request to get user information follow Withings Api document it always return result with error code.
I've tried some way but it didn't work. Can someone help me to solve this problem.
Withings Api http://www.withings.com/en/api#documentation
First i call withings action in WithingsController.groovy to get authentication.
After authenticate success server return access token, in withingsCallback action i get user information.
Result return when get user information is result code of Withings Api
{"status":2554}
This is my code
WithingsService.groovy
def getAuthDetails(callbackUrl) {
if (!authService) {
authService = new ServiceBuilder()
.provider(WithingsApi.class)
.apiKey( grailsApplication.config.oauth.withings.key as String )
.apiSecret( grailsApplication.config.oauth.withings.secret as String )
.callback( callbackUrl as String )
.build();
}
Token requestToken = authService.getRequestToken();
[ authUrl : authService.getAuthorizationUrl(requestToken), requestToken : requestToken ]
}
def getWithingsUserInformation(Token accessToken,String userId){
String url = 'http://wbsapi.withings.net/user?action=getbyuserid&userid='+userId;
OAuthRequest request = new OAuthRequest( Verb.POST, url )
authService.signRequest(accessToken, request)
Response response = request.send()
return response
}
def getAccessToken( params, requestToken ){
requestToken = requestToken as Token
Verifier verifier = new Verifier( params.oauth_verifier )
authService.getAccessToken(requestToken, verifier);
}
WithingsController.groovy
def withings() {
def authInfo = withingsService.getAuthDetails(createLink(action: 'withingsCallback', controller: 'withings', absolute: 'true'))
if (authInfo.requestToken)
{
session["withings_requestToken"] = authInfo.requestToken
}
}
def withingsCallback(){
def accessToken = withingsService.getAccessToken(params, session["withings_requestToken"])
session["withings_accessToken"] = accessToken
if(accessToken) {
def profile
String userId = params.userid
profile = withingsService.getWithingsUserInformation(accessToken,userId)
}
}
Unless I'm missing something, it looks like you are not redirecting your user to get the "access token". After you get a request token:
you then generate a authentication url
redirect the user to this authentication url
they will authenticate
if authentication is successful, provider will call your callback with access token
So your withings action should include:
def withings() {
def authInfo = withingsService.getAuthDetails(createLink(action: ....
if (authInfo.requestToken)
{
session["withings_requestToken"] = authInfo.requestToken
}
//are you missing this?
redirect(authInfo.authUrl)
}
If you're using some type of http debugging/logging, check for the following request after your withings action.
https://oauth.withings.com/account/authorize?
oauth_callback=http%3A%2F%2Fexample.com%2Fget_access_token
&oauth_consumer_key=c331c571585e7c518c78656f41582e96fc1c2b926cf77648223dd76424b52b
&oauth_nonce=369f9ceb2f285ac637c9a7e9e98019bd
&oauth_signature=OR9J9iEl%2F2yGOXP2wk5c2%2BWtYvU%3D
&oauth_signature_method=HMAC-SHA1
&oauth_timestamp=1311778988
&oauth_token=5bb105d2292ff43ec9c0f633fee9033045ed4643e9871b80ce586dc1bf945
&oauth_version=1.0
Though this is unrelated to the question initially asked, I thought I would post here since this was a common stopping ground for me reaching a Withings 2554 error.
If updating to the newest version of Withings Api for access token authentication, the current version of the Withings Api will now also cause this 2554 status code if you do not attach action: requesttoken to the access token request body.
Additionally, when pulling apart the response, make sure to drill into the body of the payload, since the latest version of the Withings access token api delivers its payload contents differently. This may be a no brainer for those implementing from scratch, but if you are using an oauth library, most of this behavior is abstracted by the library, and it likely won't be anticipating the payload structure to contain the body field.
more info here: https://developer.withings.com/api-reference#operation/oauth2-getaccesstoken

Require Google to return email address as part of OAuth

I am using OAuth to access Gmail with dotNetOAuth. How can I force Google to return user's email address as part of callback after authorization?
By default, Google OAuth callback only returns the token secret and access tokens.
First you need to add the following scope (https://www.googleapis.com/auth/userinfo.email) to your oauth request.
After you're back to your app from Google and you have your access token, you can make a request using the access token to https://www.googleapis.com/userinfo/email?alt=json.
This will return the email address. More info at http://sites.google.com/site/oauthgoog/Home/emaildisplayscope
For getting the Email Id, you need to add the scope "https://wwww.googleapis.com/auth/userinfo.email"
Then you will get id_token in the response.
Response={
"access_token" : "ya29.eAG__HY8KahJZN9VmangoliaV-Jn7hLtestkeys",
"token_type" : "Bearer",
"expires_in" : 3600,
"id_token" : "id_token_from_server",
"refresh_token" : "1/GIHTAdMo6zLVKCqNbA"
}
Then use this id_token as below POST request:
https://www.googleapis.com/oauth2/v1/tokeninfo?id_token=id_token_from_server
And you will get response like below:
Response={
"issuer": "accounts.google.com",
"issued_to": "80780.apps.googleusercontent.com",
"audience": "8078909.apps.googleusercontent.com",
"user_id": "1118976557884",
"expires_in": 3598,
"issued_at": 1456353,
"email": "emailId#gmail.com",
"email_verified": true
}
Make sure you add "www" in the APIs as shown above...
OAuth doesn't provide a facility for extra parameters during an OAuth handshake, so I don't think you can force Google to supply it. There is likely a Google API however that you can use your OAuth access token to call to fetch the email address after the handshake, however.
request OAuth scope to include the "Email Display Scope" https://www.googleapis.com/auth/userinfo.email
scope="http://www.google.com/m8/feeds/ https://www.googleapis.com/auth/userinfo.email"
Then use REST API like Hammock to get address
RestClient client = new RestClient
{
Authority = "https://www.googleapis.com",
};
RestRequest request = new RestRequest
{
Path = "userinfo/email?alt=json",
Credentials = OAuthCredentials.ForProtectedResource(
this.requestSettings.ConsumerKey,
this.requestSettings.ConsumerSecret,
this.requestSettings.Token,
this.requestSettings.TokenSecret)
};
var response = client.Request(request);
Here's a c# function for when you have pre-authorized the request as detailed above:
private void FetchUsersEmail(token)
{
var emailRequest = #"https://www.googleapis.com/userinfo/email?alt=json&access_token=" + token;
// Create a request for the URL.
var request = WebRequest.Create(emailRequest);
// Get the response.
var response = (HttpWebResponse) request.GetResponse();
// Get the stream containing content returned by the server.
var dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
var reader = new StreamReader(dataStream);
// Read the content.
var jsonString = reader.ReadToEnd();
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
dynamic json = JValue.Parse(jsonString);
var currentGoogleEmail = json.data.email;
}
(JValue is part of JSON.Net)
In php, apiOauth2Service.php class provides methods to access logged in user info. For this you can use userinfo->get() method. Make sure you also use scope https://www.googleapis.com/auth/userinfo.email.
This will work with same access token. Also you should try looking in other APIs for similar kind of information in return. This is much easier to look through oAuth_playground >> http://code.google.com/apis/explorer/
If you request the userinfo.email scope, Google returns an id_token along with the access_token.
The id_token can be unencrypted to provide the user's email address, at www.googleapis.com?/oauth2/v1/tokeninfo?id_token=IDTOKENHERE
More information here: https://developers.google.com/accounts/docs/OAuth2Login

Resources