Authentication and Authorization section in Angular 4: Beginner to Pro

Hi.

If you are doing the Angular 4: Beginner to Pro course, you may struggle with the fake-backend that Mosh has provided in the course, because some of the modules/classes that he has used in his implementation have been deprecated.

I have re-created fake-backend.ts which works with my current version of Angular which is 13.2.4. Here is the implementation:

==========================================

import { Injectable } from '@angular/core';
import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor} from '@angular/common/http';
import { Observable, of } from 'rxjs';

@Injectable()

export class fakeBackendFactory implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        const { url, method, headers, body } = request;
        let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ik1vc2ggSGFtZWRhbmkiLCJhZG1pbiI6dHJ1ZX0.1dm4jAzSnmfPFNKXAz36Iq6I1upjQ3jW1kTfv5cx2XA';

        if (url.endsWith('/api/authenticate') && method === 'POST')
            return authenticate();
        else if (url.endsWith('/api/orders') && method === 'GET')
            return getOrders();
        else
            return next.handle(request);

        function authenticate() {
            const { username, password } = JSON.parse(body);

            if (username === 'mosh@domain.com' && password === '1234')
                return of(new HttpResponse({
                status: 200,
                body: { token: token }
                }))
            else
                return of(new HttpResponse({ status: 400 }))
        }    
            
        function getOrders() {
            if (request.headers.get('Authorization') === 'bearer ' + token)
                return of(new HttpResponse({
                    status: 200,
                    body: [1, 2, 3]
                }))
            else
                return of(new HttpResponse({ status: 401 }))
        }

    }
}

==========================================

You MUST then add the following to the ‘providers’ array under @NgModule inside your app.module.ts:

{
      provide: HTTP_INTERCEPTORS,
      useClass: fakeBackendFactory,
      multi: true
    },

Hope this helps!

Happy coding.

3 Likes

Very useful, Thanks!!

1 Like