Securing the Whole App
In this lesson, we will use the token received after authentication to secure our AJAX calls.
We'll cover the following...
In the last lesson, we received the token after having authenticated the user, and now we will be sending the token to all the components needing to make an authenticated AJAX request.
We will use RxJS Subject-observables here. We will create a BehaviorSubject
holding an initial value and send the received value using the next method of the Subject. This value will then be received by all the components subscribing to this observable at any point in time.
Too much theory? Let’s look at the code and try to understand this.
First step - We will save the received token in the service using a setter.
this._tokenService.setTokenVal(this_token);
In the service,
public setTokenVal(tokenValue) {
// send the token value using next on the Subject
}
Let’s create the subject now:
@Injectable({
providedIn: 'root'
})
export class TokenService {
private _tokenProviderSubject: BehaviorSubject<string>;
public tokenProviderObservable$: Observable<string>;
constructor(private _httpReqService: HttpRequestService, private _router: Router) {
this._tokenProviderSubject = new BehaviorSubject(null);
...