facebook4j OAuth issue - facebook

I am using facebook4j i have set the configuartion details in facebook4j.properties file. But when i trying to get the accesstoken it shows
SEVERE: Error while creating the Access TokenOAuth app id/secret combination not supplied
java.lang.IllegalStateException: OAuth app id/secret combination not supplied
at facebook4j.FacebookBaseImpl.getOAuth(FacebookBaseImpl.java:247)
at facebook4j.FacebookBaseImpl.getOAuthAuthorizationURL(FacebookBaseImpl.java:213)
at facebook4j.FacebookBaseImpl.getOAuthAuthorizationURL(FacebookBaseImpl.java:206)
Could anyone can provide a example for the facebook4j for java console application
Facebook facebookClient = new FacebookFactory().getInstance();
return facebookClient;

This is how you could use facebook4j without external configuration files. The code below provides a minimal example.
Here is my simple demo:
import facebook4j.Facebook;
import facebook4j.FacebookException;
import facebook4j.FacebookFactory;
import facebook4j.auth.AccessToken;
public class Facebook4JMinimalExample {
/**
* A simple Facebook4J client.
*
*
* #param args
* #throws FacebookException
*/
public static void main(String[] args) throws FacebookException {
// Generate facebook instance.
Facebook facebook = new FacebookFactory().getInstance();
// Use default values for oauth app id.
facebook.setOAuthAppId("", "");
// Get an access token from:
// https://developers.facebook.com/tools/explorer
// Copy and paste it below.
String accessTokenString = "PASTE_YOUR_ACCESS_TOKEN_STRING_HERE";
AccessToken at = new AccessToken(accessTokenString);
// Set access token.
facebook.setOAuthAccessToken(at);
// We're done.
// Write some stuff to your wall.
facebook.postStatusMessage("Wow, it works...");
}
}
Note that it is important to FIRST make a call to "facebook.setOAuthAppId(..)" and THEN set the access token. Otherwise you'll get an IllegalStateException saying "OAuth app id/secret combination not supplied".
In this case, I've just used a default value for OAuthAppId.

Related

Proxy in Docusign Credential API

Following the Examples of Docusign SDK located at
https://github.com/docusign/DocuSign-SOAP-SDK
Trying to implement the Credential API, code is something listed below
public LoginResult getCredentialAPI() {
CredentialSoap credApi = new CredentialFactory().getCredential(credentialURL);
LoginResult result = credApi.login("[" + integratorKey + "]" + username, password, true);
return result;
}
I am getting a Connection Times out Error, The reason been I have to use Proxy connection setting to make the connection, where do I add the server URL and port for proxy connections. The class Credential Factory is listed below
public class CredentialFactory {
/**
* Builds the API interface in order to use the Docusign Credential API.
*
* #param webserviceEndpoint the endpoint for the credential webservice
* #return the credential api stub
*/
public CredentialSoap getCredential(String webserviceEndpoint) {
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
setupService(factory, webserviceEndpoint);
CredentialSoap credentialProxy = (CredentialSoap) factory.create();
return credentialProxy;
}
/**
* Set service class and webservice url.
*
* #param factory
* #param webserviceEndpoint the endpoint for the credential webservice
*/
protected void setupService(JaxWsProxyFactoryBean factory, String webserviceEndpoint) {
factory.setServiceClass(CredentialSoap.class);
factory.setAddress(webserviceEndpoint);
}
}
Proxy settings are stack-dependent. So the setting is usually below the level of the SOAP call. What stack are you using?
Judging from your variable name, you're using JAX-WS. In that case, see
https://stackoverflow.com/a/6447240/64904

Trying to get an access token using restFB. but not directing

Hello i'm playing with spring boot and learning web services. I started playing with facebook graph api and using restfb. I get the access token and hard code it every time. Now i dont always want to hard code my credentials(access tokens), i want to be able to get the token when i sign in into my account without hard coding the access tokens every time i try to retrieve my photos from face and use it in my application. Has anyone worked with restfb show me an example of how to automatically get the access tokens without hard coding it. Thanks. My uri is just "localhost:8080/myapp."
#Controller
#RequestMapping("/")
public class HomeController {
#Value("#{faceBookappId['APP_KEY']}")
private static String APP_KEY;
#Value("#{faceBookappSecret['SECRET']}")
private static String APP_SECRET;
private FacebookClient.AccessToken getFaceBookUserToken(String code, String url) throws IOException {
WebRequestor web = new DefaultWebRequestor();
WebRequestor.Response accessTokens = web.executeGet("https://graph.facebook.com/oauth/access_token?client_id="+
APP_KEY+url+"&client_secret="+APP_SECRET+"&code=" + code);
return DefaultFacebookClient.AccessToken.fromQueryString(accessTokens.getBody());
}
#RequestMapping(method= RequestMethod.GET)
public String helloFaceBook(Model model) {
String url = "https://www.facebook.com/dialog/oauth?"+APP_KEY;
return "redirect"+url;
}
}
You can use the obtainUserAccessToken from the DefaultFacebookClient
FacebookClient facebookClient = new DefaultFacebookClient(Version.VERSION_2_2);
facebookClient.obtainUserAccessToken(appId, appSecret, redirectUri, verificationCode);

zend framework1.12 rest services for web and mobile app

im new to zend framework and would like to create a web portal which offers a services .
The services would be used by webapplication and mobile application both.
I'm using Chris Danielson's article
http://www.chrisdanielson.com/2009/09/02/creating-a-php-rest-api-using-the-zend-framework/) as the base for.
My question is am i going in the right direction .currently im accessing the services as
http://www.zendrestexample.com/version .
1) I require it to use the url as http://www.zendrestexample.com/api/version
instead.
2)Do i need to use zend restserver for writing services ?
3)can i use the same service for both mobile app and the web app ?I mean any redirects problem arise?
4)Do i need to usezend rest client to consume those service ?
Pleas help me out..
Well you are not using bunch of PHP files to get this done... so I think you are on the right track =). The implementation in the article is okay, but very old... was written > 4 years ago. I would suggest looking into Zend_Soap_Server, Zend_Json_Server or Zend_Rest_Server. Soap solution is a bit heavy for the mobile in my opinion.
Just decide on the implementation and do little planning!
I wrote a web application and later had to add services layer in order to add mobile app interface to the application. Unfortunately this was not part of initial requirements so had to redo many things.
My advice is as follows (if you webapp and api are in a same project):
code all your application logic in library or in controller helpers. So same code can be reused in the main web application and in API layer
code your webapp logic in default module
code your api layer in a dedicated module called 'api'
phpdoc must be perfect in order for zend to autogenerate the SMD
For the API use standard JSON-RPC 2.0 protocol, there are clients for both Android / iPhone that utilize this and provide auto-discovery (SMD like WSDL but for json). All request sent via GET result in SMD being displayed all others result in handling of the request.
Utilize Zend_Json_Server for your API layer.
Here is an functional example :
<?php
// API Controller Example
class ApiController extends Zend_Controller_Action
{
public function init()
{
parent::init();
$this->getHelper('ViewRenderer')->setNoRender();
}
public function helloWorldAction()
{
$this->_handleRequest('App_Api_HelloWorld');
}
protected function _handleRequest($handlerClassName)
{
//
$this->getHelper('ViewRenderer')->setNoRender();
//
$server = new Zend_Json_Server();
$server->setClass($handlerClassName);
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$cfg = Zend_Registry::get('config');
$req = $this->getRequest();
$reqUrl = $cfg->paths->basehref . $req->getControllerName() . '/' . $req->getActionName();
$server->setTarget($reqUrl)
->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);
$smd = $server->getServiceMap();
header('Content-Type: application/json');
echo $smd;
} else {
// handle request
$server->handle();
}
}
}
// HANDLER Class Example
class App_Api_HelloWorld extends App_Api_ApiHandlerAbstract
{
/**
* says "hello world"
*
* #return string
*/
public function hello()
{
return 'hello world';
}
/**
* says "hello $name"
*
* #param string $name
* #return string
*/
public function hello2($name)
{
return "hello $name";
}
/**
*
* #return string
* #throws Exception
*/
public function hello3()
{
throw new Zend_Json_Server_Exception('not allowed');
return '';
}
}
Here is sample Request (I added some bootstrap magic to pickup session by id)
https://domain.com/api/hello-world
{
"session_id": "4ggskr4fhe3lagf76b5tgaiu57",
"method": "hello2",
"params": {
"name" : "Alex"
},
"id": 123
}
Review JSON RPC 2.0 Documentation.
I found Advanced REST Client for Google Chrome to be BEST extension for developing and testing JSON web services.
For additional security you can restrict ALL the request via HTTP Auth by adding few lines of code to the abstract controller or even create security controller plugin.
Good Luck.

Facebook with DotNetOpenAuth 4.1.0.12182

I'm attempting to create a user login for Facebook and Windows LiveId using DotNetOpenAuth 4.1.0.12182
However the examples in the download make use of DotNetOpenAuth.ApplicationBlock and DotNetOpenAuth.ApplicationBlock.Facebook which don't exist in the current build.
Instead there is the DotNetOpenAuth.AspNet.Clients namespace which includes FacebookClient and WindowsLiveClient - however I can't find any example of how to use these.
Do any examples or documentation exist?
I have been able to get DNOA version 4.1.0.12182, .Net 3.5 and Facebook to work with each other by creating a FacebookAuthClient that is derived off of the DotNetOpenAuth.OAuth2.WebServerClient. One little gotcha that I have found is that if you are using cookie based sessions then you have to access the session before you use the OAuth functionality. From what I can tell this is because DNOA uses the Session ID as the state parameter and if session has never been accessed it can change between requests. This will cause a state parameter mismatch error when the response comes back from Facebook.
FacebookAuthClient:
public class FacebookAuthClient : DotNetOpenAuth.OAuth2.WebServerClient
{
private static readonly DotNetOpenAuth.OAuth2.AuthorizationServerDescription Description = new DotNetOpenAuth.OAuth2.AuthorizationServerDescription
{
TokenEndpoint = new Uri("https://graph.facebook.com/oauth/access_token"),
AuthorzationEndpoint = new Uri("https://graph.facebook.com/oauth/authorize")
};
public static readonly string [] ScopeNeeded = { "publish_stream" };
public FacebookAuthClient()
: base(Description)
{
}
}
Facebook.aspx.cs:
public partial class FacebookPage : System.Web.UI.Page
{
private FacebookAuthClient _client = new FacebookAuthClient
{
ClientIdentifier = ConfigurationManager.AppSettings["FBClientId"], //The FB app's Id
ClientCredentialApplicator = DotNetOpenAuth.OAuth2.ClientCredentialApplicator.PostParameter(ConfigurationManager.AppSettings["FBClientSecret"]) // The FB app's secret
}
protected void Page_Load(object sender, EventArgs e)
{
DotNetOpenAuth.OAuth2.IAuthorizationState auth = _client.ProcessUserAuthorization();
if (_auth == null)
{
// Kick off authorization request with the required scope info
client.RequestUserAuthorization(FacebookAuthClient.ScopeNeeded);
}
}
}
This is just a test app so there is no error handling but it seems to work.
Edit
I used the DotNetOpenAuth(unified) NuGet package for all of this.
Edit
Added missing .PostParameter call to the creating of the ClientCredentialApplicator.
You'll need to use ctp version 3.5 of DNOA. Version 4+ has been made to work with a later draft of OAuth 2 then Facebook uses.
You can find it on the owners GitHub:
https://github.com/AArnott/dotnetopenid

Handling sessions in JSF while working with socialauth API, for login

I have been working with social auth API in JSF, for getting an login with facebook, I dont know whether am creating a session properly. I have searched some stuffs form internet and doing it. Now i have caught up with some error.
according to social auth first we need to call a function, which helps to get the authentication URL from the Facebook, where i need to create a session and and set attributes to it, with the parameters from facebook once user logs in into the facebook.
so my first view page will just contain,
a command button to call the respective function.
<h:form><h:commandButton value="submit" action="#{socialNetworkAuthentication.facebookAuthentication}"></h:commandButton></h:form>
then the function which is called ...
public String facebookAuthentication(){
try{
//Create an instance of SocialAuthConfgi object
SocialAuthConfig config = SocialAuthConfig.getDefault();
String propUrl="oauth_consumer.properties";
//load configuration. By default load the configuration from oauth_consumer.properties.
//You can also pass input stream, properties object or properties file name.
config.load(propUrl);
//Create an instance of SocialAuthManager and set config
SocialAuthManager manager = new SocialAuthManager();
manager.setSocialAuthConfig(config);
//URL of YOUR application which will be called after authentication
String successUrl = "http://chennaivolunteers.com/ChennaiVolunteers/faces/cv/employee-profile.xhtml";
// get Provider URL to which you should redirect for authentication.
// id can have values "facebook", "twitter", "yahoo" etc. or the OpenID URL
String url = manager.getAuthenticationUrl("facebook", successUrl);
// Store in session
HttpServletRequest request=(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpSession ses = request.getSession(true);
ses.setAttribute("authManager", manager);
System.out.println(url);
FacesContext.getCurrentInstance().responseComplete();
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
}
then finally i redirect to the respective URL given by the facebook, after user logs in into the facebook, then it automatically moves to the succesURL which is was mentioned in the above code.
In my successURL i just have an outputtext.
<tr><td class="profile-head"><h:outputText id="name" value="#{employeeProfile.profileName}" /></td></tr>
<tr><td class="content-black">
<div class="padding-2"><h:outputText id="name" value="#{employeeProfile.profileName}" />
In the backing bean, i created a session to get the attributes which i set earlier.
public class EmployeeProfile {
public String profileName;
public String getProfileName() throws Exception {
HttpServletRequest request=(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpSession ses = request.getSession(true);
SocialAuthManager m = (SocialAuthManager)ses.getAttribute("authManager");
AuthProvider provider = m.connect(SocialAuthUtil.getRequestParametersMap(request));
Profile p = provider.getUserProfile();
String userName=p.getFirstName();
System.out.println(userName);
return userName;
}
public void setProfileName(String profileName) {
this.profileName = profileName;
}
when i printed the username in console it does, but its not the view page of this backing bean, have caught up with two exceptions as below.
1. javax.faces.FacesException: Could not retrieve value of component with path : {Component-Path : [Class: javax.faces.component.UIViewRoot,ViewId: /cv/employee-profile.xhtml][Class: javax.faces.component.html.HtmlOutputText,Id: name]}
Caused by: javax.el.ELException: /cv/employee-profile.xhtml at line 133 and column 105 value="#{employeeProfile.profileName}": Error reading 'profileName' on type socialServlet.EmployeeProfile
2.javax.faces.FacesException: This is not the same SocailAuthManager object that was used for login.Please check if you have called getAuthenticationUrl() method before calling connect()
Caused by: This is not the same SocailAuthManager object that was used for login.Please check if you have called getAuthenticationUrl() method before calling connect()
Last one is just an inbuilt exception of social auth API,
But i dont think any problem in this, because when i try it out with servlet, everything works fine, i think am doing some mistake in JSF session. But i dont know wher i am wrong.
My problem is now rectified.. the mistake i did is, i have invoked the connect() function again. Now i have did everything in the constructor itself. It works fine.
public class EmployeeProfile {
public EmployeeProfile() throws Exception {
// TODO Auto-generated constructor stub
ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
HttpServletRequest request = (HttpServletRequest)ectx.getRequest();
HttpSession session = request.getSession(true);
SocialAuthManager m = (SocialAuthManager)session.getAttribute("authManager");
AuthProvider provider = m.connect(SocialAuthUtil.getRequestParametersMap(request));
Profile p = provider.getUserProfile();
String userName=p.getFirstName();
System.out.println(userName);
setProfileName(userName);
setBirthDate(p.getDob());
setImageUrl(p.getProfileImageURL());
p.getGender();
}