Friday, November 21, 2014

Login with Facebook for a community with Visualforce

Adding an auth provider (e.g., Login with Facebook) to a Salesforce Communities instance is pretty easy.

The Login with ... button is pretty magical: It knows what community you're logging into, and it knows what URL you're trying to access upon authentication. Based on that information when you click the button, you're taken to the correct authentication URL based on the Auth Provider configuration in Salesforce.

But... for orgs that have customized their login pages with Visualforce, how do you add this button? Luckily, adding the same magical button to a custom Visualforce login page doesn't require you to manually reconstruct the OAuth authentication endpoint. Instead, you can just use the AuthConfiguration.getAuthProviderSsoUrl() method.

Simply put, you need just three things:
  • Your community's base URL
  • The relative path after the base URL to which the user should be taken upon successful authentication. This is also known as the startUrl.
  • The URL Suffix (a.k.a. DeveloperName) of your auth provider (e.g., Facebook) as configured in Salesforce

Once you have this information, all you need to do is create an action in your Apex controller that returns a PageReference object, constructed from the URL returned by AuthConfgiuration.getAuthProviderSsoUrl().

This same approach can be applied to other auth providers as well, such as Twitter or Google.