Node.js REST API Facebook Login
Ivan Vasiljevic
1.4K12

Excellent tutorial, much appreciated! I just followed it to get myself set up and I want to add these updates for anyone just starting now with the latest Angular and Node versions:

I would recommend installing “@auth0/angular-jwt” instead of “angular2-jwt”, as the latter doesn’t work with the newer “rxjs” package (currently version 6 as of this writing) that your project will be using.

As a result, there are some changes to make to some files.

  1. Here’s how you must set up your main app.module.ts file. See the “@auth0/angular-jwt” npmjs page for better instructions, but here’s what mine looks like:
// add these lines:
import { HttpClientModule } from '@angular/common/http';
import { JwtModule } from '@auth0/angular-jwt';
// remove any imports from angular2-jwt if you started the tutorial with them, in fact you can "npm uninstall angular2-jwt" at this point
// remove the getAuthHttp function if you copied from the tutorial
// remove the object that used getAuthHttp() in the "providers" array if you copied from the tutorial
// add these to your imports array:
// ...
HttpClientModule,
JwtModule.forRoot({
// see https://www.npmjs.com/package/@auth0/angular-jwt for how this works
config: {
headerName: 'x-auth-token',
authScheme: '', // gets rid of "Bearer " prefix
tokenGetter: (() => localStorage.getItem('id_token')),
whitelistedDomains: ['localhost', 'example.com'],
blacklistedRoutes: ['example.com/example_auth_route/']
}
}),

2. Here’s how you must change the user.service.ts file:

// remove the import from angular2-jwt, add the below instead
// '@auth0/angular-jwt' uses the standard Angular HttpClient
// instead of requiring its own - perhaps via some kind
// of extension behind-the-scenes
import { HttpClient } from '@angular/common/http';
// now use the HttpClient in the constructor, like so...
constructor(private http: HttpClient) {
/*****
in the http.post call's response-handling, I couldn't figure out how to get at the headers, so instead in the server I set "x-auth-token" as a field in the body of data being returned. Here is how that client-side code looks now:
******/
return this.http.post(this.apiPrefix + "/api/v1/auth/facebook", {access_token: result.authResponse.accessToken,
observe: 'response'})
.toPromise()
.then((response: any) => {
var token = response['x-auth-token'];
if (token) {
localStorage.setItem('id_token', token);
}
resolve(response);
})

3. Minor change to server — as noted above, I couldn’t figure out how to get at the API response headers to read “x-auth-token”, so I simply changed the server’s sendToken() function to remove res.setHeader('x-auth-token', req.token); and replace it with req.auth['x-auth-token'] = req.token;