Skip to content

Instantly share code, notes, and snippets.

@mustakim
Last active July 7, 2022 11:55
Show Gist options
  • Save mustakim/1b87b92b10e4c1855bb6493fa132d4cc to your computer and use it in GitHub Desktop.
Save mustakim/1b87b92b10e4c1855bb6493fa132d4cc to your computer and use it in GitHub Desktop.
social-auth-wiki

Social Auth with Angular (eg: Linkedin, Facebook, Google, Apple)

Note: The entire login process cannot be handled from client side, backend integration required for some steps

Linkedin with Angular

Step-1: Create your app in linkedin developer console

In order to start with linkedin login, we need to first create out app in linkedin.

Note: If you have already created your app, click on Go to My apps, select your app and then follow from step no 1.2

Click on the Create app button and fill up all the mandatory fields (App name, Company, Business email and App logo).

Note: In the company field you need to select a page from the dropdown results or create new company page. (For testing purpose, just type test and select any random page from the dropdown list)

At the end, accept the legal terms and click on the Create app button

1.2: Get the client id

Copy the client id from the Auth tab

1.3: Add a redirect url

We need to add a redirect url in order to get back the auth token provided by linkedin after successful authentication.

For example, if our app's web url is http://www.awesomeapp.com We can add redirect url as http://www.awesomeapp.com/linkedinLoginResponse (we will setup this route in the upcoming steps), you can add localhost URL for test in development

Linkedin setup done!

Step-2: Configure angular app to handle linkedin login

2.1: Setup 2 pages (components)

Minimum 2 pages (routes) required to handle LinkedIn login properly in our angular app. One page to place the Login with linkedin button and another one to handle linkedin redirection. Let say we are naming them as login & linkedInLoginResponse

The minimum content for the component login

login.component.html

<button (click)="login()">Login with LinkedIn</button>

login.component.ts

import { Component } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";

@Component({
  selector: "LoginComponent",
  templateUrl: "./login.component.html",
  styleUrls: ["./login.component.css"],
})
export class LoginComponent {
  linkedInCredentials = {
    clientId: "************",
    redirectUrl: "<Your Redirect URL>",
    scope: ["r_liteprofile", "r_emailaddress"],
  };

  constructor(private http: HttpClient) {}

  login() {
    window.location.href = `https://www.linkedin.com/uas/oauth2/authorization?
    response_type=code
    &client_id=${this.linkedInCredentials.clientId}
    &redirect_uri=${this.linkedInCredentials.redirectUrl}
    &scope=${this.linkedInCredentials.scope}`;
  }
}

The minimum content for the component linkedInLoginResponse

linkedinLoginResponse.component.html

<p>Your linkedIn code = {{ linkedInToken }}</p>

linkedinLoginResponse.component.ts

import { Component, OnInit } from "@angular/core";
import { Router, ActivatedRoute, Params } from "@angular/router";

@Component({
  selector: "LinkedinLoginResponse",
  templateUrl: "./linkedinLoginResponse.component.html",
  styleUrls: ["./linkedinLoginResponse.component.css"],
})
export class LinkedinLoginResponse implements OnInit {
  linkedInToken = "";

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.linkedInToken = this.route.snapshot.queryParams["code"];
  }
}

2.2: Setup Routes in your app module

app.module.ts

...
import { Routes, RouterModule, Router } from "@angular/router";
...
import { LoginComponent } from "./login/login.component";
import { LinkedinLoginResponse } from "./linkedinLoginResponse/linkedinLoginResponse.component";

const routes: Routes = [
  { path: "", redirectTo: "/login", pathMatch: "full" },
  { path: "login", component: LoginComponent },
  { path: "linkedInLogin", component: LinkedinLoginResponse }
];

@NgModule({
  declarations: [AppComponent, LoginComponent, LinkedinLoginResponse],
  imports: [BrowserModule, RouterModule.forRoot(routes)],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Don't forget to put router-outlet in app.component.html

app.component.html

<router-outlet></router-outlet>

Step-3: Configure backend to complete the process

Once we get the authoriazation_code from linked in we need to send the authoriazation_code to our backend service which will exchange the auth token and get user details (name, email etc) from linkedin.

3.1: Send the authoriazation_code to backend service

3.2: Exchange auth token from linkedin

Send a post request to https://www.linkedin.com/oauth/v2/accessToken with params

{
    grant_type: "authorization_code",  // value of this field should always be: 'authorization_code'
    code: "The authorization code you received from client side",
    redirect_uri: "https://y8pud.codesandbox.io/linkedInLogin",  // The same redirect_url used in step 2.1 (in login.component.ts)
    client_id: 'Client ID of your linkedapp', // Follow step 1.2
    client_secret: 'secret key of your linkedapp'   // Follow step 1.2
}

A successful access token request returns a JSON object containing the following fields:

access_token — The access token for the application. This value must be kept secure as specified in the API Terms of Use. expires_in — The number of seconds remaining until the token expires. Currently, all access tokens are issued with a 60 day lifespan.

3.3: Get user details

Send a get request to https://www.linkedin.com/oauth/v2/me with params

{
  Authorization: "Bearer <access_token>";
}

A successful request returns a JSON object containing informations which was declared in the scope

Facebook with Angular

0: Create your app in facebook developer account

In order to start with facebook, please sign in (or sign up if there is no account) with faceboo.

1.2: Create Facebook Login app and set Redirect URL which is collected from Firebase Auth.

1.3 Add App ID, App Secret from Basic setting to Firebase Auth App.

After that, same as linkedin process, we can get facebook information according to scopes.

Google with Angular

1.1: In the authentication part, select Add new privider and add google.

After that, same as facebook process, we can get google information according to scopes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment