I sent this request in my Java application: https://www.facebook.com/dialog/oauth?client_id=CLIENT_ID&redirect_uri=https://www.facebook.com/connect/login_success.html&scope=email.
Next I showed the authorization page which was received as response. After submitting login info nothing happens
In redirect_uri you should set link on your site(for example: http://localhost/facebook-auth).
So you will get request like this one:
http://localhost/facebook-auth/?code=AQD5q80zafjvVZoZex87ROxkCvWT9rZhjwZtkBLajYwH20KztPOI0jpb5lHZisPd3mA49Wu_onAeEioU5K6KVuoCliznf61B5bDfZSLFaIn6E7E49zqs4fO6NjTYyxN43LBttCvsSlirJOAtbOpB3oyMrl3bbjlPhGHsCyJzA-DypEIZ1c_36WAEBPmfSq3TroekvTLme3jIzZk0C-93cu8z#_=_
This code param you need to get the token.
Your next query will be like:
$params = array(
'client_id' => $client_id,
'redirect_uri' => $redirect_uri,
'client_secret' => $client_secret,
'code' => $_GET['code']
);
$url = 'https://graph.facebook.com/oauth/access_token';
And in response you will get the token
Related
There is a php code to prepare a bundle for sending notification to firebae :
$registrationIds = array( $_GET['id'] );
// prep the bundle
$msg = array
(
'body' => $_GET['body'],
'title' => $_GET['title'],
'vibrate' => 1,
'sound' => 1,
);
$fields = array
(
'registration_ids' => $registrationIds,
'notification' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
I want same in java, i did all well and getting response 200 from firebase.
but i dont know how to get registration-id . As done in php like :
$registrationIds = array( $_GET['id'] );
Please help me to find out the registration-id.
To get the registrationId of a device(iOS or Android) the device needs to send/store it in a DB some where. I recommend using the realtime database provided by firebase.
First to get registrationId from the iOS App. Use let token = FIRInstanceID.instanceID().token(). This Token is known as the registrationId
Take this token and store it in your DB.
Server side you need to get that token out of your DB and place it as the value for the registration_ids or as the value for the "to" key. That should be it.
What about the "to"
So it's well laid out on how to use "to" in this StackoverflowPost
You don't get the "to" parameter from the client.
I am trying to access data on LinkedIn profile using its API.
At first I followed the LinkedIn JSPAI Doc on https://developer-programs.linkedin.com/documents/exchange-jsapi-tokens-rest-api-oauth-tokens in PHP. So I started translating code from PHP to Java using Scribe.
Then, I have found this example on Github which looks like what I did : https://github.com/fernandezpablo85/TokenExchangeSample/blob/master/src/main/java/com/linkedin/oauth/ExchangeService.java
and I got this string in the end after authorization and cookie exchange :
oauth_token=75--4ff2c506-37e2-4b77-927f-c28c5f511762&oauth_token_secret=c73110b2-0dce-43bd-8537-8c8fb4fd5290&oauth_expires_in=5183975&oauth_authorization_expires_in=5183975
In PHP, the listed code help to get user data as described in the $url :
// go to town, fetch the user's profile
$url = 'http://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline)';
$oauth->fetch($url, array(), OAUTH_HTTP_METHOD_GET, array('x-li-format' => 'json')); // JSON!
$profile = json_decode($oauth->getLastResponse());
print "$profile->firstName $profile->lastName is $profile->headline.";
So the code works and returns data. In the Java version, I am wondering how to use the returned tokens.
I tried used https://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline)?oauth_token=75--7ff2c506-57e2-4b77-927f-c28c5f551762&oauth_token_secret=c73330b2-0dce-48bd-8537-8c8fb4fd5290&oauth_expires_in=5183975&oauth_authorization_expires_in=5183975
But it does not work.
I found the solution : After getting the Oauth10a keys, you should use them in a new Request by specifying the json format.
OAuthService service = new ServiceBuilder()
.apiKey(APIKEY)
.apiSecret(SECRETKEY)
.provider(LinkedInApi.class)
.build();
OAuthRequest oAuthRequestData = new OAuthRequest(Verb.GET, DATAENDPOINT);
oAuthRequestData.addHeader("x-li-format", "json");
Token accessToken = new Token(oauth_token, oauth_token_secret);
service.signRequest(accessToken, oAuthRequestData);
Response oAuthResponse = oAuthRequestData.send();
System.outt.println(oAuthResponse.getBody());
I am trying to removing facebook requests by using graph api :
DELETE https://graph.facebook.com/[<REQUEST_OBJECT_ID>_<USER_ID>]?access_token=[USER or APP ACCESS TOKEN]
Like this:
DeleteMethod method = new DeleteMethod("https://graph.facebook.com/requestId_userId?access_token=token");
HttpClient httpClient = new HttpClient();
httpClient.executeMethod(method);
Server sends me status code 400 but when I open this link on browser FB returns me information about request. What I doing wrong?
I resolved this problem using attribute "method" in http request and replacing user access token on app access token like this:
https://graph.facebook.com/[requestId_userId]?access_token=[appToken]&method=delete
this url works on all requests types: post, get and delete.
If you use the C# facebook SDK you can use this:
var fb = new FacebookClient(Config.FacebookAppId, Config.FacebookAppSecret);
var result = fb.Delete(string.Format("{0}_{1}?access_token={2}", facebookRequestId, facebookUserId, fb.AccessToken));
I just started looking at scribe for authentication with social networks such as twitter/facebook etc. I am using the example for twitter as reference. However, I don't seem to get oauth_verifier from twitter for some reason (even though the callback is registered through the service builder - I am using localhost in the callback as it worked with another social api). Any helpful suggestions would be quite welcome. thanks in advance.
OAuthService service = new ServiceBuilder()
.provider(TwitterApi.class)
.apiKey(consumerKey)
.apiSecret(consumerSecret)
.callback("http://localhost/oauth/twitter")
.build();
//get the token
Token requestToken = service.getRequestToken();
String authUrl = service.getAuthorizationUrl(requestToken);
Logger.info("authurl::" + authUrl); // not getting the oauth_verifier
Debug output from scribe (I changed the token info):
setting oauth_callback to http://localhost/oauth/twitter
generating signature...
base string is: POST&http%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%253A%252F%252Flocalhost%252Foauth%252Ftwitter%26oauth_consumer_key%3DAAACCCV6ASDFGHJCgYBCD%26oauth_nonce%3D607134093%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1353965859%26oauth_version%3D1.0
signature is: +mSqKJIC1Q0pMEFs/gIJViF7kbg=
appended additional OAuth parameters: { oauth_callback -> http://localhost/oauth/twitter , oauth_signature -> +mSqKJIC1Q0pMEFs/gIJViF7kbg= , oauth_version -> 1.0 , oauth_nonce -> 607134093 , oauth_signature_method -> HMAC-SHA1 , oauth_consumer_key -> AAACCCV6ASDFGHJCgYBCD , oauth_timestamp -> 1353965859 }
using Http Header signature
sending request...
response status code: 200
response body: oauth_token=itJrpOP3KLeD7Ha6oy0IRr4HysFut5eAOpIlj8OmNE&oauth_token_secret=X8LmhAUpvIkfEd7t7P1lvwwobC3JJIhUabcEs0Rn5w&oauth_callback_confirmed=true
authurl::https://api.twitter.com/oauth/authorize?oauth_token=itJrpOP3KLeD7Ha6oy0IRr4HysFut5eAOpIlj8OmNE
obtaining access token from http://api.twitter.com/oauth/access_token
setting token to: Token[itJrpOP3KLeD7Ha6oy0IRr4HysFut5eAOpIlj8OmNE , X8LmhAUpvIkfEd7t7P1lvwwobC3JJIhUabcEs0Rn5w] and verifier to: org.scribe.model.Verifier#55ac8c3d
generating signature...
Update:
I am able to receive the oauth_verifier now. I will update this post once I am done testing.
pilot error mostly. I was able to get oauth working with twitter using scribe. After getting the service, the request Token from the service & then the authorizationUrl from the service (while passing in the request token), I was able to redirect to the authorization URL. Once there, I was able to authenticate myself against twitter using my twitter ID which redirected me to the callback URL specified when I created the service. Upon authentication, I received the oauth_verifier which I was able to use to create the verifier & then receive the access token from the service using the verifier and the request token. Then the oauth request was made & signed which resulted in the response from twitter with the user details. Worked. Hope it helps.
We're creating a Java client to interface with a Ruby on Rails server for an inventory system project (for school).
The client that we're using is supposed to do HTTP GET's to request information and HTTP POST's to update or create new information (yes, we know about HTTP PUT...).
Unfortunately, we are running into a InvalidAuthenticityToken error when we try to do a HTTP post. We authenticate through HTTP basic authentication and our controllers look like this:
class UsersController < ApplicationController
before_filter :authenticate
def show
#user = User.find(params[:id])
##user = User.all
render :xml => #user.to_xml
end
def update
#user = User.find(params[:id])
if #user.update_attributes(params[:user])
render :text => 'Success!'
else
render :text => 'No success!'
end
end
private
def authenticate
logger.info("Entering Authen..")
authenticate_or_request_with_http_basic do |username, password|
logger.info("Time: #{Time.now}, username: #{username}, password: #{password}")
User.authenticate(username, password)
end
end
end
The show action works perfectly and the authentication action is triggered with a valid username and password (e.g., working fine...). Our problem happens when we attempt to POST an update to the update action. When we attempt it, we get an InvalidAuthenticityToken exception. The following is from our development log:
#Successful GET
Processing UsersController#show (for 10.18.2.84 at 2010-11-24 19:02:42) [GET]
Parameters: {"id"=>"2"}
Entering Authen..
Filter chain halted as [:authenticate] rendered_or_redirected.
Completed in 3ms (View: 2, DB: 0) | 401 Unauthorized [http://10.18.2.84/users/show/2]
Processing UsersController#show (for 10.18.2.84 at 2010-11-24 19:02:43) [GET]
Parameters: {"id"=>"2"}
Entering Authen..
Time: Wed Nov 24 19:02:43 -0600 2010, username: admin, password: pass
[4;36;1mUser Load (1.0ms)[0m [0;1mSELECT * FROM "users" WHERE (user_name = 'admin' AND password = 'pass') LIMIT 1[0m
[4;35;1mUser Load (0.0ms)[0m [0mSELECT * FROM "users" WHERE ("users"."id" = 2) [0m
Completed in 18ms (View: 2, DB: 1) | 200 OK [http://10.18.2.84/users/show/2]
#Unsuccessful POST
Processing UsersController#update (for 10.18.2.84 at 2010-11-24 19:03:06) [POST]
Parameters: {"id"=>"2", "first-name"=>"Macky"}
ActionController::InvalidAuthenticityToken
(ActionController::InvalidAuthenticityToken):
Our concern is that it isn't even attempting to authenticate the basic authentication -- it's skipping the filter and the entire controller as far as we can tell. Our code is pretty vanilla in the client (this is edited down for comprehensibility from what it actually is):
DefaultHttpClient httpClient = new DefaultHttpClient();
myCredentials = new UsernamePasswordCredentials( username, password );
//Set Provider
provider = new BasicCredentialsProvider();
provider.setCredentials(scope, myCredentials);
//Set Credentials
httpClient.setCredentialsProvider( provider );
ArrayList<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("first-name", "Macky"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
//Set the post
post = new HttpPost( url );
post.setEntity(formEntity);
response = httpClient.execute( post );
So, is it with Rails that we're doing something wrong or is it with the Java Jakarta client? Any help is greatly appreciated.
Are you including the CSRF token in your POST data?
See this link: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html
By default protect_from_forgery is enabled which makes Rails require an authenticity token for any non-GET requests. Rails will automatically include the authenticity token in forms created with the form helpers but I'm guessing since you're building your own form to post, you're not including the token.