How to integrate login with facebook button in Java EE project?

I want to integrate the login with facebook button in my Java EE web application. What is the best method?

I am using jsf primefaces 3.5. Thank.

+3
source share
1 answer

I use AuthenticRoast to login to Facebook in Java-EE applications (JSF 2.1 deployed to GF 3/4).

On its website:

AuthenticRoast allows you to create highly flexible authentication mechanisms for the Java Web tier. It can be anything from HTTP Basic authentication to authenticate using openid, facebook, or your Kerberos setup company. Authentication modules can be combined as desired and even modified at runtime.

, , ServletContextListener:

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import name.aikesommer.authenticator.Registry;


public class ARDAppInit implements ServletContextListener
{
    @Override
  public void contextInitialized( ServletContextEvent sce )
  {
    ServletContext sc = null;
    sc = sce.getServletContext();
    // register AuthenticRoast authenticator extending CompositeAuthenticator 
    Registry.forContext( sc ).register( new YouCustomAuthenticatorImpl());   
  } 

    @Override
    public void contextDestroyed(ServletContextEvent sce) {


    }

}

web.xml.

<listener>
    <listener-class>it.elbuild.package.package.ARDAppInit</listener-class>
</listener>

, , CompositeAuthenticator. - YouCustomAuthenticatorImpl.

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import name.aikesommer.authenticator.CompositeAuthenticator;
import name.aikesommer.authenticator.LogoutManager;
import name.aikesommer.authenticator.PluggableAuthenticator;

/**
 * 
 * 
 * @author ELbuild, web applications and more...
 */

public class YouCustomAuthenticatorImpl extends CompositeAuthenticator {

@Override
protected Collection<PluggableAuthenticator> createAuthenticators() {
    List<PluggableAuthenticator> result = new ArrayList();

    /**
     * Allow form-based logins.
     */
    result.add(new ARDFormAuthenticator());

    /**
     * Allow Facebook-based logins.
     */
    result.add(new FacebookAuthenticator());

    /**
     * Allow a user to "logout".
     */
    result.add(new LogoutManager());

    return result;
}

}

, FB, , . , Facebook. - PluggableAuthenticator.

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import it.elbuild.bjj.db.base.DAOFactory;
import it.elbuild.bjj.entities.Profile;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import name.aikesommer.authenticator.AuthenticationRequest;
import name.aikesommer.authenticator.PluggableAuthenticator;
import name.aikesommer.authenticator.SimplePrincipal;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.FacebookApi;
import org.scribe.model.*;
import org.scribe.oauth.OAuthService;

/**
 *
 * @author ELbuild, web applications and more...
 */
public class FacebookAuthenticator extends PluggableAuthenticator {

    private static final String PRINCIPAL_NOTE = PluggableAuthenticator.class.getName() + ".PRINCIPAL";
    public static final String LOGIN_ACTION = "/j_facebook_login";
    public static final String REDIRECT_ACTION = "/j_facebook_redirect";
    public static final String CODE = "code";
    OAuthService service = null;

    /**
     * Overwrite this to specify a different login-page.
     */
    protected String getLoginPage() {
        return "/login.jsp";
    }

    /**
     * Overwrite this to specify a different error-page.
     */
    protected String getErrorPage() {
        return "/login-error.jsp";
    }

    protected String getRegisterPage() {
        return "/register.xhtml";
    }

    protected String getRedirectPage(String url) throws UnsupportedEncodingException {

        String encode = "ISO-8859-1";

        String data = URLEncoder.encode(url, encode);


        return "/social-login.xhtml?redirectto=" + data;
    }

    /**
     * Overwrite this to specify a different path to direct to, if there is no
     * original request.
     */
    protected String getNextPath() {
        return "/";
    }

    @Override
    public AuthenticationRequest.Status tryAuthenticate(PluggableAuthenticator.AuthenticationManager manager, AuthenticationRequest request) {
        if (manager.matchesRequest(request) && request.getSessionMap().containsKey(PRINCIPAL_NOTE)) {
            manager.register(request, (SimplePrincipal) request.getSessionMap().get(PRINCIPAL_NOTE));
            request.getSessionMap().remove(PRINCIPAL_NOTE);
            manager.restoreRequest(request);
            return AuthenticationRequest.Status.Success;
        }

        String requestURI = request.getRequestPath();
        boolean loginAction = requestURI.endsWith(LOGIN_ACTION);

        if (loginAction) {

            String facebookId = checkCredentials(manager, request);

            if (facebookId != null) {
                request.getSessionMap().put(PRINCIPAL_NOTE, loadPrincipal(manager, request, facebookId));
                String queryString = request.getHttpServletRequest().getQueryString();
                if (queryString != null && queryString.length() > 0) {
                    manager.addQueryString(request, queryString);
                }
                if (manager.hasRequest(request)) {
                    manager.redirectToRequest(request);
                } else {
                    manager.saveRequest(request, getNextPath());
                    manager.forward(request, getNextPath());
                }
                return AuthenticationRequest.Status.Continue;
            }



            manager.forward(request, getRegisterPage() + "?facebook=facebook");
            return AuthenticationRequest.Status.Continue;
        } else {
            boolean redirectAction = requestURI.endsWith(REDIRECT_ACTION);
            if (redirectAction) {
                redirect(manager, request);
                return AuthenticationRequest.Status.Continue;
            }
        }

        return AuthenticationRequest.Status.None;
    }

    @Override
    public AuthenticationRequest.Status authenticate(PluggableAuthenticator.AuthenticationManager manager, AuthenticationRequest request) {
        manager.saveRequest(request);
        manager.forward(request, getLoginPage());
        return AuthenticationRequest.Status.Continue;
    }

    @Override
    public AuthenticationRequest.ManageAction manage(PluggableAuthenticator.AuthenticationManager manager, AuthenticationRequest request) {
        return AuthenticationRequest.ManageAction.None;
    }

    public void redirect(PluggableAuthenticator.AuthenticationManager manager, AuthenticationRequest request) {
        try {
            service = new ServiceBuilder()
                    .provider(FacebookApi.class)
                    .apiKey("YOUR API KEY HERE")
                    .apiSecret("YOUR API SECRET HERE")
                    .callback("YOUR CALLBACK HERE")
                    .debug()
                    .build();

            // Obtain the Authorization URL
            String url = service.getAuthorizationUrl(null);


            manager.forward(request, getRedirectPage(url));
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(FacebookAuthenticator.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public String checkCredentials(PluggableAuthenticator.AuthenticationManager manager, AuthenticationRequest request) {
        String code = request.getParameter(CODE);
        Verifier verifier = new Verifier(code);

        // Trade the Request Token and Verfier for the Access Token
        Token accessToken = service.getAccessToken(null, verifier);
        System.out.println("Got the Access Token!");
        System.out.println("(if your curious it looks like this: " + accessToken + " )");
        System.out.println();

        // Now let go and ask for a protected resource!
        System.out.println("Now we're going to access a protected resource...");
        OAuthRequest orequest = new OAuthRequest(Verb.GET, "https://graph.facebook.com/me");
        orequest.addBodyParameter("get", "name");

        service.signRequest(accessToken, orequest);
        Response response = orequest.send();
        System.out.println("Got it! Lets see what we found...");
        System.out.println();
        System.out.println(response.getBody());
        JsonParser parser = new JsonParser();
        JsonObject authData = parser.parse(response.getBody()).getAsJsonObject();



        String facebookId = authData.getAsJsonPrimitive("id").getAsString();
        Profile p = null;

        if (facebookId != null) {
            p = DAOFactory.getProfileDAO().findByFacebookId(facebookId);
        }
        if (p == null) {
            return null;
        } else {
            return facebookId;
        }
    }

    protected SimplePrincipal loadPrincipal(AuthenticationManager manager, AuthenticationRequest request, String facebookId) {
        Profile p = DAOFactory.getProfileDAO().findByFacebookId(facebookId);

        return new SimplePrincipal(p.getUserName(), p.getUserRole());
    }
}
+2

All Articles