Skip to Content

How to use Facebook login in Angular?

How to use Facebook login in Angular?

Facebook login has become a popular way for web applications to quickly onboard users without requiring them to create new accounts. By using Facebook login, users can leverage their existing Facebook accounts to sign in to a web app in just a few clicks.

Integrating Facebook login into an Angular application is straightforward with the Angular OAuth2 library. In this comprehensive guide, we’ll walk through the entire process step-by-step:

Overview

Here is a quick overview of adding Facebook login to an Angular app:

  • Register your app with Facebook Developers to get an app ID and app secret
  • Install the Angular OAuth2 library
  • Configure the OAuth module with your app credentials
  • Add a login button that initiates the OAuth flow
  • Make API calls to Facebook to get user profile data
  • Save the user’s access token for subsequent API calls

We’ll cover each of these steps in detail in the following sections.

Prerequisites

Before we dive in, you’ll need the following:

  • An existing Angular app generated with Angular CLI
  • A Facebook developer account to register your app
  • Node.js and npm installed globally

Let’s now set up a Facebook app to get the credentials we need in our Angular app.

Step 1: Register a Facebook App

Head over to Facebook for Developers and log in with your developer account. Click ‘+ Add App’ to create a new app:

Enter a display name and contact email for your app. Select ‘Business’ for the type and move on:

On the dashboard page for your new app, click on ‘Add Products’ and select ‘Facebook Login’ as the product:

Under the ‘Quickstart’ section, the most important piece of information we need is the ‘App ID’. Copy this somewhere as we’ll need it soon:

We also need an app secret, which acts like a password for making API calls from our app. To generate a secret, click on ‘Settings’ > ‘Basic’ on the left nav bar. Scroll down to ‘App Secret’ and click ‘Show’ to reveal the secret:

Copy the app secret and store it securely, as it should not be revealed publicly. We now have the two credentials we need from Facebook!

Step 2: Install Angular OAuth2 Library

The angular-oauth2-oidc library makes it easy to integrate various OAuth 2.0 identity providers in an Angular app. It handles the authentication flow and token management automatically.

Install it via npm:

npm install angular-oauth2-oidc --save

Once installed, import the main module:

import { OAuthModule } from 'angular-oauth2-oidc';

And add it to your app module’s imports:

@NgModule({
  //...
  imports: [
    OAuthModule.forRoot()
  ]
})
export class AppModule {}

This sets up the core OAuth functionality we’ll build on top of.

Step 3: Configure the OAuth Module

We now need to configure the OAuth module with our app credentials. This will involve:

  • Registering Facebook as the identity provider
  • Supplying the client ID and secret
  • Configuring the OAuth endpoints

Open your app.module.ts and add the following configuration:

const fbLoginConfig = {

  // Your Facebook appId
  issuer: 'https://www.facebook.com',

  // URL of your app to allow return from Facebook login
  redirectUri: window.location.origin + '/index.html',

  // Your Facebook appId
  clientId: '1234567890678', 

  // Your Facebook app secret
  secret: 'aBcDeFgHiJkLmNoPqRsTuVwXyZaBcDeFgH',

  // URL of Facebook auth server that returns auth code 
  authorizationEndpoint: 'https://www.facebook.com/v4.0/dialog/oauth',

  // URL of your server that exchanges auth code for token
  tokenEndpoint: 'https://graph.facebook.com/v4.0/oauth/access_token',

  // URL of Facebook's userinfo endpoint
  userinfoEndpoint: 'https://graph.facebook.com/v4.0/me?fields=id,name,email,picture', 
  
  // URL where to load Facebook's JS SDK from
  loadUserProfileAtStartUp: true,

  // Scope for user data we want
  scope: 'email,public_profile',

  showDebugInformation: true,
};

@NgModule({
  // ...

  imports: [
    OAuthModule.forRoot({
      resourceServer: {
        // Leave undefined to not use resourceServer
      }
    }),
  ],

  providers: [
    {
      provide: 'FB_LOGIN_CONFIG',
      useValue: fbLoginConfig,
    },
  ],
})
export class AppModule {}

This provides the necessary endpoints and credentials for the OAuth service to work.

Step 4: Add a Login Button

We’re now ready to implement a simple Facebook login button. In your component template, add:

<oauth-login 
  provider="FB_LOGIN_CONFIG">
  Login with Facebook
</oauth-login>

The <oauth-login> component from the library renders a button to trigger the login process. Clicking the button will open the Facebook auth page and return to the callback URL upon completion.

Step 5: Get User Profile Information

After a successful login, we likely want to retrieve detailed profile information about the user from Facebook. The OAuth service provides events we can subscribe to for this.

In your component class, inject the OAuthService and add:

constructor(private oauthService: OAuthService) {

  this.oauthService.events
    .pipe(filter(e => e.type === 'token_received'))
    .subscribe(_ => {

      // Get user profile data from Facebook
      this.oauthService.loadUserProfile().then(profile => {
        console.log(profile);  
      });

    });

} 

This listens for the ‘token_received’ event that fires after a successful login. We then use the loadUserProfile() method to fetch the user’s data from Facebook using the token.

The profile object contains fields like name, email, gender, birthdate, location etc. depending on the requested scopes.

Step 6: Save the Access Token

When the user logs in, an access token is generated that allows us to make API calls to Facebook on behalf of that user.

This token expires after a certain period, so we need to persist it in order to access their data again later without having to re-authenticate.

Let’s save the token to localStorage when received:

this.oauthService.events
  .subscribe(e => {
    if (e.type === 'token_received') {
      // Store token
      window.localStorage.setItem('fb_token', e.token);
    }
  });

We can then retrieve it later to make Facebook API calls:

// Fetch stored token
const fbToken = localStorage.getItem('fb_token');

// Use token to call Facebook API
const resp = await fetch(`https://graph.facebook.com/me?fields=id,name&access_token=${fbToken}`); 

This allows us to access their Facebook profile across multiple sessions until the token expires.

Advanced Usage

We’ve covered the basics of integrating Facebook login, but there’s a few other useful things we can do:

Custom Scopes

By default, Facebook provides basic profile information like name and email after login. We can request additional permissions from the user via custom scopes:

// In app config
scope: 'email,user_posts' 

// This will allow accessing their posts after login

See Facebook’s docs on permissions for all available options.

Auto-Refreshing Tokens

Access tokens expire after a few hours by default. The OAuth library can automatically refresh them in the background when making API calls:

// In app config
autoRefreshToken: true
silentRefreshRedirectUri: '/silent-refresh.html'

This avoids needing to re-prompt the user to log in again once the token expires.

Validating Facebook Responses

It’s good practice to verify the authenticity of data returned by Facebook. We can do this by validating the response signature:

import { FacebookResponseValidator } from 'angular-oauth2-oidc-facebook';

// Validate signature
const validator = new FacebookResponseValidator();
const isValid = validator.validate(responseFromFacebook);

This helps prevent issues if the data was manipulated between Facebook and our app.

Handling Logout

To allow users to log out, simply call the logOut() method:

this.oauthService.logOut();

This will clear the access token from storage and revoke permissions granted to the app.

You can also reset the authentication state with:

this.oauthService.resetAuthorizationData();

Conclusion

That covers the major steps to get Facebook login working in Angular! Some key points:

  • Register an app and get credentials from the Facebook Developer dashboard
  • Install and configure the angular-oauth2-oidc library
  • Use the <oauth-login> component to initiate login
  • Subscribe to OAuth events to take action after login
  • Make Facebook API calls to get user profile data
  • Persist the access token to avoid re-logging in
  • Validate responses from Facebook for security

Facebook login provides a quick and easy authentication system for apps. Integrating it with Angular using the OAuth library streamlines the entire process.

Some other enhancements like custom scopes or auto-refreshing tokens provide deeper Facebook integration once the basics are in place.

Hopefully this gives you a good foundation for adding Facebook login to your own Angular apps! Let me know if you have any other questions.