Getting Facebook error 11 - facebook

I am using
version 5.0 of BBplugin in eclipse and the FB jar lib ( FacebookBlackBerrySDK-v0.8.25.jar )
i get an error
API error code :11
API Error Description : This method is deprecated
Error Message: Display=wap dialogs have have been deprecated . You can temporarily enable them by disabling the "july_2012" migration.They will stop working permanently on july 1,2012.
http://supportforums.blackberry.com/t5/Java-Development/FaceBook-API-error-code-11-Method-Deprecated/td-p/1671793
I checked out this link ..
But it isn't giving the solution
I tried out for july 2012 migration solution only
i have not tried the solution display=wap into display=touch
as i don't know where it is
i get the following error when i run it on simulator
http://tinypic.com/view.php?pic=191m3o&s=6
import com.blackberry.facebook.ApplicationSettings;
import com.blackberry.facebook.Facebook;
import com.blackberry.facebook.FacebookException;
import com.blackberry.facebook.inf.User;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.container.MainScreen;
public class MyScreen extends MainScreen implements FieldChangeListener{
private User user;
String NEXT_URL = "http://www.facebook.com/connect/login_success.html";
String APPLICATION_ID = "My App id"
String APPLICATION_SECRET = "My Application Secret";
String[] PERMISSIONS = Facebook.Permissions.ALL_PERMISSIONS;
private Facebook fb;
private ApplicationSettings as;
private String id="";
private EditField ef;
private ButtonField bf;
public MyScreen(String id ) {
// this.user = user;
this.id = id;
ef = new EditField("Hi", " ");
bf = new ButtonField("Publish");
bf.setChangeListener(this);
add(ef);
add(bf);
}
private void FBPost(){
ApplicationSettings as = new ApplicationSettings(NEXT_URL, APPLICATION_ID, APPLICATION_SECRET, PERMISSIONS);
Facebook fb = Facebook.getInstance(as);
as = new ApplicationSettings(NEXT_URL, APPLICATION_ID, APPLICATION_SECRET, PERMISSIONS);
fb = Facebook.getInstance(as);
try {
user = fb.getCurrentUser();
String result = user.publishStatus(ef.getText());
if ((result != null) && !result.trim().equals("")) {
Dialog.inform("Publish Success.");
} else {
Dialog.inform("Publish Failed.");
}
} catch (FacebookException e) {
// TODO Auto-generated catch block
Dialog.inform("Exception in myscreen");
e.printStackTrace();
}
}
public void fieldChanged(Field field, int context) {
if(field==bf){
String text = ef.getText();
FBPost();
}
}
}
Above is my code Please
check out

Check your app setting on facebook. and in Migrations disable last three options(July 2012 Breaking Changes, Include Checkins with Statuses, August 2012 Breaking Changes).Hope it will help you :)

Related

HTTP Basic Authentication for Play framework 2.4

I am looking some way to make some authentication for my play framework app: I want allow/disallow the whole access to non authenticated users
Is there exists some working module/solution for it? I don't need any forms for auth, just 401 HTTP response for non authenticated users (like Apache .htacccess "AuthType Basic" mode).
I've updated Jonck van der Kogel's answer to be more strict in parsing the authorization header, to not fail with ugly exceptions if the auth header is invalid, to allow passwords with ':', and to work with Play 2.6:
So, BasicAuthAction class:
import java.io.UnsupportedEncodingException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.apache.commons.codec.binary.Base64;
import play.Logger;
import play.Logger.ALogger;
import play.mvc.Action;
import play.mvc.Http;
import play.mvc.Http.Context;
import play.mvc.Result;
public class BasicAuthAction extends Action<Result> {
private static ALogger log = Logger.of(BasicAuthAction.class);
private static final String AUTHORIZATION = "Authorization";
private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
private static final String REALM = "Basic realm=\"Realm\"";
#Override
public CompletionStage<Result> call(Context context) {
String authHeader = context.request().getHeader(AUTHORIZATION);
if (authHeader == null) {
context.response().setHeader(WWW_AUTHENTICATE, REALM);
return CompletableFuture.completedFuture(status(Http.Status.UNAUTHORIZED, "Needs authorization"));
}
String[] credentials;
try {
credentials = parseAuthHeader(authHeader);
} catch (Exception e) {
log.warn("Cannot parse basic auth info", e);
return CompletableFuture.completedFuture(status(Http.Status.FORBIDDEN, "Invalid auth header"));
}
String username = credentials[0];
String password = credentials[1];
boolean loginCorrect = checkLogin(username, password);
if (!loginCorrect) {
log.warn("Incorrect basic auth login, username=" + username);
return CompletableFuture.completedFuture(status(Http.Status.FORBIDDEN, "Forbidden"));
} else {
context.request().setUsername(username);
log.info("Successful basic auth login, username=" + username);
return delegate.call(context);
}
}
private String[] parseAuthHeader(String authHeader) throws UnsupportedEncodingException {
if (!authHeader.startsWith("Basic ")) {
throw new IllegalArgumentException("Invalid Authorization header");
}
String[] credString;
String auth = authHeader.substring(6);
byte[] decodedAuth = new Base64().decode(auth);
credString = new String(decodedAuth, "UTF-8").split(":", 2);
if (credString.length != 2) {
throw new IllegalArgumentException("Invalid Authorization header");
}
return credString;
}
private boolean checkLogin(String username, String password) {
/// change this
return username.equals("vlad");
}
}
And then, in controller classes:
#With(BasicAuthAction.class)
public Result authPage() {
String username = request().username();
return Result.ok("Successful login as user: " + username + "! Here's your data: ...");
}
You can try this filter:
https://github.com/Kaliber/play-basic-authentication-filter
It looks pretty simple to use and configure.
You could also solve this with a play.mvc.Action, like this.
First your Action:
import org.apache.commons.codec.binary.Base64;
import play.libs.F;
import play.libs.F.Promise;
import play.mvc.Action;
import play.mvc.Http.Context;
import play.mvc.Result;
import util.ADUtil;
public class BasicAuthAction extends Action<Result> {
private static final String AUTHORIZATION = "authorization";
private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
private static final String REALM = "Basic realm=\"yourRealm\"";
#Override
public Promise<Result> call(Context context) throws Throwable {
String authHeader = context.request().getHeader(AUTHORIZATION);
if (authHeader == null) {
context.response().setHeader(WWW_AUTHENTICATE, REALM);
return F.Promise.promise(new F.Function0<Result>() {
#Override
public Result apply() throws Throwable {
return unauthorized("Not authorised to perform action");
}
});
}
String auth = authHeader.substring(6);
byte[] decodedAuth = new Base64().decode(auth);
String[] credString = new String(decodedAuth, "UTF-8").split(":");
String username = credString[0];
String password = credString[1];
// here I authenticate against AD, replace by your own authentication mechanism
boolean loginCorrect = ADUtil.loginCorrect(username, password);
if (!loginCorrect) {
return F.Promise.promise(new F.Function0<Result>() {
#Override
public Result apply() throws Throwable {
return unauthorized("Not authorised to perform action");
}
});
} else {
return delegate.call(context);
}
}
}
Next your annotation:
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import play.mvc.With;
#With(BasicAuthAction.class)
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.METHOD, ElementType.TYPE})
#Inherited
#Documented
public #interface BasicAuth {
}
You can now annotate your controller functions as follows:
#BasicAuth
public Promise<Result> yourControllerFunction() {
...
I'm afraid there's no such solution, reason is simple: usually when devs need to add authorization/authentication stack they build full solution.
The easiest and fastest way is using HTTP front-end server as a reverse-proxy for your application (I'd choose nginx for that task, but if you have running Apache on the machine it can be used as well). It will allow you to filter/authenticate the traffic with common server's rules
Additionally it gives you other benefits, i.e.: you can create CDN-like path, so you won't waste your apps' resources for serving public, static assets. You can use load-balancer for redeploying your app without stopping it totally for x minutes, etc.

Can't login with facebook in Windows Phone App

It was working fine before but It's not working even though I haven't changed anything in my Facebook related code. It is giving this error:
App doesn't give permission to given URL : The settings of app doesn't allow one or more of the given URL's. URLs must be Website's URL or Canvas URL...
Here is my FacebookLoginPage.cs:
namespace MyApp.Pages
{
public partial class FacebookLoginPage : PhoneApplicationPage
{
private string message;
public FacebookLoginPage()
{
InitializeComponent();
message = String.Empty;
this.Loaded += FacebookLoginPage_Loaded;
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
NavigationService.GoBack();
base.OnBackKeyPress(e);
}
private async void FacebookLoginPage_Loaded(object sender, RoutedEventArgs e)
{
if (String.IsNullOrEmpty(App.AccessToken))
{
App.isAuthenticated = true;
await Authenticate();
}
}
private FacebookSession session;
private async Task Authenticate()
{
//Facebook logini kontroli eğer login olduysa AccessToken ve bilgileri çeker.
try
{
if (App.FacebookSessionClient.LoginInProgress == true && !String.IsNullOrEmpty(message))
{
App.FacebookSessionClient.LoginInProgress = false;
}
else
{
session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream");
App.AccessToken = session.AccessToken;
App.appSettings["accessToken"] = App.AccessToken;
App.appSettings.Save();
App.FacebookId = session.FacebookId;
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Pages/MainPage.xaml?token=" + App.AccessToken, UriKind.Relative)));
}
}
catch (InvalidOperationException)
{
message = "failed";
App.FacebookSessionClient.LoginInProgress = true;
NavigationService.GoBack();
}
}
}
}
What might be the probelm?
When I added facebook.com to Oauth part of Advanced Setting in my Facebook App, the problem solved. Thanks to the following link: Windows Phone 8 Facebook Login Given URL is not allowed by the application

Error using facebook C# sdk with WPF web browser

I am new to facebook c# sdk. I followed the tutorial in this link.
I created an application that displays the user name after log in. Here is my code:
public partial class MainWindow : Window
{
private string appId = "appid";
private string extenededPermissions = "offline_access,publish_stream";
private Uri loginUrl = null;
private string accessToken = null;
private string userName = null;
public MainWindow()
{
InitializeComponent();
}
/// <summary>
/// Function to get the login url
/// with the requested permissions
/// </summary>
private void GetLoginUrl()
{
dynamic parameters = new ExpandoObject();
// add the client id
parameters.client_id = appId;
// add the redirect uri
parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
// requested response
parameters.response_type = "token";
// type of display
parameters.display = "popup";
// If extended permissions are present
if (!string.IsNullOrWhiteSpace(extenededPermissions))
parameters.scope = extenededPermissions;
// Create the login url
Facebook fc = new FacebookClient();
loginUrl = fc.GetLoginUrl(parameters);
}
private void WindowLoaded(object sender, RoutedEventArgs e)
{
// get the login url
GetLoginUrl();
// Navigate to that page
webBrowser.Navigate(loginUrl);
}
private void webBrowser_Navigated(object sender, NavigationEventArgs e)
{
var fc = new FacebookClient();
FacebookOAuthResult fr;
// Check the returned url
if (fc.TryParseOAuthCallbackUrl(e.Uri, out fr))
{
// check if authentication is success or not
if (fr.IsSuccess)
{
getUserName(out userName);
}
else
{
var errorDes = fr.ErrorDescription;
var errorReason = fr.ErrorReason;
}
}
else
{
}
}
private void getUserName(out string name)
{
var fb = new FacebookClient(accessToken);
// Get the user details
dynamic result = fb.Get("me");
// Get the user name
name = result.name;
MessageBox.Show("Hai " + name + ",Welcome to my App");
}
}
My Problem is with the FacebookOAuthResult.
private void webBrowser_Navigated(object sender, NavigationEventArgs e)
{
var fc = new FacebookClient();
FacebookOAuthResult fr;
// Check the returned url
if (fc.TryParseOAuthCallbackUrl(e.Uri, out fr))
{
// check if authentication is success or not
if (fr.IsSuccess)
{
getUserName(out userName);
}
else
{
var errorDes = fr.ErrorDescription;
var errorReason = fr.ErrorReason;
}
}
else
{
}
}
After I logged in it is redirecting to redirect_uri. But the fc.TryParseOAuthCallbackUrl(e.Uri, out fr) fails though the webbrowser redirects to the Authentication successful page.
So I couldn't get the access token. What could the problem in my code be?
This doesn't answer the question, but I see you are asking for an offline_access permission. Facebook removed offline_access sometime ago. Instead you need an Extended Access Token. You get it by exchanging the access token you are trying to get, for an extended one. They last for about 2-3 months after which you have to get a new one.
Nevermind i have found out the solution..Thanks to the answers for the question!
I have added the Winforms web browser control to the wpf and the authentication is working.The problem is with WPF web browser. It simply omits the url after # token So the parseurl won't able to authenticate it.
Here's the modified code..
private void WindowLoaded(object sender, RoutedEventArgs e)
{
// create the windows form host
System.Windows.Forms.Integration.WindowsFormsHost sample =
new System.Windows.Forms.Integration.WindowsFormsHost();
// create a new web browser
webBrowser = new System.Windows.Forms.WebBrowser();
// add it to winforms
sample.Child = webBrowser;
// add it to wpf
canvas1.Children.Add(sample);
webBrowser.Navigated += webBrowser_Navigated;
webBrowser.Navigate(loginURL);
}
void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
// do the authentication
var fc = new FacebookClient();
FacebookOAuthResult fr;
// Check the returned url
if (fc.TryParseOAuthCallbackUrl(e.Url, out fr))
{
// check if authentication is success or not
if (fr.IsSuccess)
{
accessToken = fr.AccessToken;
// Actions to do
}
else
{
var errordes = fr.ErrorDescription;
var errorreason = fr.ErrorReason;
}
}
else
{
//Not a valid url
}
}
The problem is solved!!

How use SocialAuth with JSF to redirect?

I'm trying to use SocialAuth, the idea is very simple, click in log in with facebook then redirect the user to my website signed in.
The log in part I get it, which is below :
1) /index.xhtml
<h:form id="login-facebook">
<h:commandButton id="login" action="#{socialFacebook.login}" value="Login"/>
</h:form>
2) socialFacebook bean
package controller;
#ManagedBean(name="socialFacebook")
#RequestScoped
public class SocialFacebook implements Serializable{
private static final long serialVersionUID = -4787254243136316495L;
private String code;
#PostConstruct
public void init(){
try {
HttpServletRequest request=(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
SocialAuthManager manager = (SocialAuthManager)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("authManager");
Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request);
AuthProvider provider = manager.connect(paramsMap);
// get profile
Profile p = provider.getUserProfile();
System.out.println(p.getFullName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void login(){
try {
HttpServletRequest request=(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
//Create an instance of SocialAuthConfig object
SocialAuthConfig config = SocialAuthConfig.getDefault();
//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();
//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://localhost:8080/cc/pages/system/login_facebook.xhtml" + ";jsessionid=" + req.getSession().getId();
String successUrl = "http://localhost:8080/cc/pages/system/index.xhtml" + ";jsessionid=" + request.getSession().getId();
// 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
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("authManager", manager);
//redirect to the successful login page
FacesContext.getCurrentInstance().responseComplete();
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
3) Facebook returned the following URL:
http://localhost:8080/cc/pages/system/home_facebook.xhtml;jsessionid=e143aa975fa3f313c677fbcb03e3?code=AQAmJXdQX0B__zJHXnRyPfgaG1CfNUEEEEEEEEEEEEEEEZJLEpsT5s1spd3KtWGWI2HYaIOZKLkrn8axKs4iKwJVQJwJQB_WSs2iWkp2DDDDDDDDDDDDtdRPLPG7psp6r2PYmn7CTm2QNNha7f1QlgmoZtBsIEF0SSSSSSSSSSSSSSSSSSSSSSS8RutAU8dqI2KDE57f#_=_
4) It pass by my init method as BalusC suggest but always prints nope :( :
#ManagedBean(name="redirectFacebook")
#RequestScoped
public class RedirectFacebook implements Serializable{
private static final long serialVersionUID = -566276017320074630L;
private String code;
private Profile profile;
#PostConstruct
public void init(){
try {
HttpServletRequest request=(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpSession session = (HttpSession) request.getAttribute("jsessionid");
if (request.getAttribute("code") != null)
System.out.println("code");
else
System.out.println("nope :(");
if (session != null){
SocialAuthManager manager = (SocialAuthManager)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("authManager");
Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request);
AuthProvider provider = manager.connect(paramsMap);
// get profile
profile = provider.getUserProfile();
System.out.println(profile.getFullName());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
5) And it prints nope :( too in my home_facebook page:
<h:form id="redirect-facebook-form">
<f:metadata>
<f:viewParam name="code" value="#{redirectFacebook.code}" />
</f:metadata>
<h:panelGroup rendered="#{not empty redirectFacebook.profile}">
Hello, you're successfully associated as #{socialFacebook.profile.firstName} on Facebook
</h:panelGroup>
<h:panelGroup rendered="#{empty redirectFacebook.profile}">
Nope :(
</h:panelGroup>
</h:form>
But, I'm a bit confuse how to get the result in my bean and do some verifications as if the user is registered or not for instance. I know, looking some code in Google, that I have to do this, but how can I redirect to my bean and do this and redirect the user to the proper page ?
SocialAuthManager manager = (SocialAuthManager)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("authManager");
Map<String, String> paramsMap = SocialAuthUtil.getRequestParametersMap(request);
AuthProvider provider = manager.connect(paramsMap);
// get profile
Profile p;
p = provider.getUserProfile();
This is really taking some nights to figure it out.
Any idea is very appreaciated, thanks.
I don't see any code level issue except you are using localhost in URL.
Here is a wiki link which describes how to run application with localhost.
Please let me know if this does not work.

Facebook oAuth implementation for blackberry

I am working on a blackberry native application, which uses the features like Facebook and twitter sharing of messages. After goggling I found that I could make use of Facebook SDK in order to integrate with Facebook service.
I have downloaded the SDK from this link https://sourceforge.net/projects/facebook-bb-sdk/
I have followed the steps that are being explained in the README pdf file, which was bundled with SDK. I have followed the below steps
Step1: Getting Facebook façade instance
String NEXT_URL = "http://www.facebook.com/connect/login_success.html";
String APPLICATION_ID = "15355516805e272"; // my app id
String APPLICATION_SECRET = "354f91a79c8fe5a8de9d65b55ef9aada"; // my app secret key
String[] PERMISSIONS = Facebook.Permissions.USER_DATA_PERMISSIONS;
ApplicationSettings as = new ApplicationSettings(NEXT_URL, APPLICATION_ID,
APPLICATION_SECRET, PERMISSIONS);
Facebook fb = Facebook.getInstance(as);
Step2: Retrieving current user
fb.getCurrentUser(new BasicAsyncCallback() {
public void onComplete(com.blackberry.facebook.inf.Object[]
objects, final java.lang.Object state) {
user = (User) objects[0];
// do whatever you want
}
public void onException(final Exception e, final
java.lang.Object state) {
e.printStackTrace();
// do whatever you want
}
});
Step3: Publish user status.
user.publishStatus("Hello world!");
But, it gives IOException and nothing happens. I am sure many people have done similar things earlier. I am looking for a source explains step by step process of integrating with Facebook service.
This code works for me. it shows how to get the current user and publish status
public class FacebookHelper {
private final String NEXT_URL = "http://www.facebook.com/connect/login_success.html";
private final String APPLICATION_ID = "123456789";
private final String APPLICATION_SECRET = "123456789123456789123456789123456789";
String[] PERMISSIONS = Facebook.Permissions.PUBLISHING_PERMISSIONS;
User user;
Facebook fb;
ApplicationSettings as = new ApplicationSettings(NEXT_URL, APPLICATION_ID,
APPLICATION_SECRET, PERMISSIONS);
public FacebookHelper() {
fb = Facebook.getInstance(as);
}
public void publishContent(final String content) {
try {
fb.getCurrentUser(new BasicAsyncCallback() {
public void onComplete(
com.blackberry.facebook.inf.Object[] objects,
final java.lang.Object state) {
user = (User) objects[0];
user.publishStatus(content);
}
public void onException(final Exception e,
final java.lang.Object state) {
System.out.println("Exception inside BasicAsyncCallback " + e.toString()
+ " , " + e.getMessage());
}
});
} catch (Exception e) {
System.out.println("Exception in publishContent " + e.toString() + " , "
+ e.getMessage());
}
}
}
I have recently implemented Facebook & Twitter Integration into my Blackberry 7 Based Application. What i Found with this, Facebook API having Errors and even it is in Beta version.Please try Following API: FacebookAPIMe and TwitterAPIMe. If you have any problem in implementing this APIs, i will help you.Both are Simple to Use and Easily integrated with your application.Both are Containing Example App so You can also view Demo of that API.