2

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.

Valter Silva
  • 16,446
  • 52
  • 137
  • 218
  • Most straightfoward way would be doing the job in (post)constructor of a request/view scoped bean associated with the callback page `home.xhtml`. Have you tried this? – BalusC Feb 28 '13 at 00:50
  • Yes, I did, the `request` I always `NULL`. How can I associate the callback page with the bean ? – Valter Silva Feb 28 '13 at 01:03
  • Just reference the bean somewhere in the page, e.g. `Hello, you're successfully associated as #{socialAuthBean.profile.username} on Facebook` and so on. Or, via ``. – BalusC Feb 28 '13 at 01:12
  • @BalusC, I update my post and bean, it seems the right thing to do as you suggested, but keep getting this error `SEVERE: org.brickred.socialauth.exception.SocialAuthException: Verification code is null`. – Valter Silva Feb 28 '13 at 01:19
  • You should not do it in the postconstructor of the bean which is used for login. It would try to find the facebook profile right before the enduser actually logs in on facebook. You should do it in a separate bean associated with the callback request. Or are you using the same page for login and callback? – BalusC Feb 28 '13 at 01:24
  • I will do in another page as you suggested then. I was using the same page. Just a sec and I back ;) – Valter Silva Feb 28 '13 at 01:29
  • @BalusC, I update my post once more. Now with the steps that my project is doing. Still not working, but now I get it how get the answer from facebook in my bean throught the `@PostContruct`. I just don't get why I can't get the `request`. – Valter Silva Feb 28 '13 at 01:45
  • @BalusC, I still don't get it how this is working.. could you please help me ? – Valter Silva Feb 28 '13 at 04:13
  • 2
    The `code` is a request parameter, not a request attribute. Plus, `jsessionid` can and should not be obtained this way, the container handles this transparently. Use `request.getParameter()` or `externalContext.getRequestParameterMap()` to get a request parameter. – BalusC Feb 28 '13 at 11:29
  • @BalusC Hello there. I am from one year later, and I'm using the same page for login and callback. [How do I manage the user profile in the session](http://stackoverflow.com/questions/23747930/jsf-login-with-facebook-socialauth-and-keeping-session-alive)? – Georgian May 19 '14 at 22:32

1 Answers1

0

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.

Amol M Kulkarni
  • 21,143
  • 34
  • 120
  • 164