Adding the HttpInterceptor in the AppModule

It goes without saying that our AuthInterceptor class will only work if we properly configure it within our AppModule class. To do that, open the app.module.shared.ts file and add the following (new code highlighted):

[...]

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { RouterModule } from '@angular/router';

import { AuthService } from './services/auth.service';
import { AuthInterceptor } from './services/auth.interceptor';

[...]

providers: [
AuthService,
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
]

[...]

If we did everything correctly, now the token should be automatically added to each HTTP request. We can easily test it from the server side by placing a breakpoint at the start of the QuizController.GetLatest() method, that gets called each time the Home view is accessed:

We can then run our application in debug mode and see what happens upon the first HTTP request:

By looking into the Request.Headers.HeaderAuthorization property--using the Visual Studio's Watch window--we should be able to see our token, the same that we got back from our TokenController a short while ago, unless we cleared our browser's localStorage; in case we did that, all we need to do is visit the Login view again and perform a new login to get another token, and then try again.

As soon as we see the Bearer token, before leaving that breakpoint and ending the debug session, we should also check out the this.User.Identity.IsAuthenticated property, which should be set to true --meaning that our user has been successfully authenticated using the token.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.110.155