Skip to content

Instantly share code, notes, and snippets.

@jamestrandung
Last active October 8, 2017 16:40
Show Gist options
  • Save jamestrandung/5279774 to your computer and use it in GitHub Desktop.
Save jamestrandung/5279774 to your computer and use it in GitHub Desktop.
Social authentication
/**
* Loads the application configuration from the given input stream Format of
* the input stream should be as follows: <br/>
* www.google.com.consumer_key = opensource.brickred.com
*
* @param inputStream
* property file input stream which contains the configuration.
* @throws Exception
*/
public void load(final InputStream inputStream) throws Exception { ... }
/**
* Loads the application configuration from the given file
*
* @param fileName
* the file name which contains the application configuration
* properties
* @throws Exception
*/
public void load(final String fileName) throws Exception { ... }
/**
* Loads the application properties from oauth_consumer.properties file.
*
* @throws Exception
*/
public void load() throws Exception { ... }
/**
* Loads the application configuration from the given properties
*
* @param properties
* application configuration properties
* @throws Exception
*/
public void load(final Properties properties) throws Exception { ... }
@Named(value = "userSession")
@SessionScoped
public class UserSessionBean implements Serializable {
private SocialAuthManager manager;
private String originalURL;
private String providerID;
private Profile profile;
public UserSessionBean() { ... }
public void socialConnect() throws Exception {
// Put your keys and secrets from the providers here
Properties props = System.getProperties();
props.put("graph.facebook.com.consumer_key", FACEBOOK_APP_ID);
props.put("graph.facebook.com.consumer_secret", FACEBOOK_APP_SECRET);
// Define your custom permission if needed
props.put("graph.facebook.com.custom_permissions", "publish_stream,email,user_birthday,user_location,offline_access");
// Initiate required components
SocialAuthConfig config = SocialAuthConfig.getDefault();
config.load(props);
manager = new SocialAuthManager();
manager.setSocialAuthConfig(config);
// 'successURL' is the page you'll be redirected to on successful login
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
String successURL = externalContext.getRequestContextPath() + "socialLoginSuccess.xhtml";
String authenticationURL = manager.getAuthenticationUrl(providerID, successURL);
FacesContext.getCurrentInstance().getExternalContext().redirect(authenticationURL);
}
public void pullUserInfo() {
try {
// Pull user's data from the provider
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
Map map = SocialAuthUtil.getRequestParametersMap(request);
if (this.manager != null) {
AuthProvider provider = manager.connect(map);
this.profile = provider.getUserProfile();
// Do what you want with the data (e.g. persist to the database, etc.)
System.out.println("User's Social profile: " + profile);
// Redirect the user back to where they have been before logging in
FacesContext.getCurrentInstance().getExternalContext().redirect(originalURL);
} else FacesContext.getCurrentInstance().getExternalContext().redirect(externalContext.getRequestContextPath() + "home.xhtml");
} catch (Exception ex) {
System.out.println("UserSession - Exception: " + ex.toString());
}
}
public void logOut() {
try {
// Disconnect from the provider
manager.disconnectProvider(providerID);
// Invalidate session
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
this.invalidateSession(request);
// Redirect to home page
FacesContext.getCurrentInstance().getExternalContext().redirect(externalContext.getRequestContextPath() + "home.xhtml";);
} catch (IOException ex) {
System.out.println("UserSessionBean - IOException: " + ex.toString());
}
}
// Getters and Setters
}
Facebook = "facebook"
Google = "google"
Twitter = "twitter"
Yahoo = "yahoo"
Hotmail = "hotmail"
LinkedIn = "linkedin"
Foursquare = "foursquare"
OpenId = Need users to enter manually
<f:view>
<ui:param name="originalURL" value="#{request.requestURI}?#{request.queryString}" />
<f:metadata>
<f:event rendered="#{empty userSession.profile}" type="preRenderView" listener="#{userSession.setOriginalURL(originalURL)}" />
</f:metadata>
</f:view>
<h:form>
<h:panelGroup rendered="#{empty userSession.profile}" id="socialButtons" >
<h:commandLink id="facebook" action="#{userSession.socialConnect}" >
<f:setPropertyActionListener target="#{userSession.providerID}" value="facebook" />
<h:graphicImage value="/images/facebook_icon.png" />
</h:commandLink>
<h:commandLink id="google" action="#{userSession.socialConnect}" >
<f:setPropertyActionListener target="#{userSession.providerID}" value="google" />
<h:graphicImage value="/images/google-icon.jpg" />
</h:commandLink>
</h:panelGroup>
<h:panelGrid columns="3" rendered="#{not empty userSession.profile}" >
<h:graphicImage rendered="#{not empty userSession.profile.profileImageURL}" value="#{userSession.profile.profileImageURL}" />
<h:outputText value="Hello, #{userSession.profile.fullName}" />
<h:commandButton value="Log out" actionListener="#{userSession.logOut}" />
</h:panelGrid>
</h:form>
SEVERE: This is not the same SocailAuthManager object that was used for login.Please check if you have called getAuthenticationUrl() method before calling connect()
at org.brickred.socialauth.SocialAuthManager.connect(SocialAuthManager.java:179)
at commonBeans.UserSessionBean.pullUserInfo(UserSessionBean.java:117)
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Social login success</title>
</h:head>
<h:body>
<h:outputText style="display:none;" value="#{userSession.pullUserInfo()}" />
</h:body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment