我想在我的Java EE Web应用程序中集成“使用Facebook登录”的按钮。最佳方法是什么?
我正在使用JSF PrimeFaces 3.5。谢谢。
我想在我的Java EE Web应用程序中集成“使用Facebook登录”的按钮。最佳方法是什么?
我正在使用JSF PrimeFaces 3.5。谢谢。
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) {
}
}
<listener>
<listener-class>it.elbuild.package.package.ARDAppInit</listener-class>
</listener>
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's 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());
}
}