I have the problem on the server side, when I refresh page there is no way to retrieve jwt token on server from local storage because of localstorage only exists on the browser. Also when I log in I save token in the transfer state and again after the page is refreshed state variable disappear, is it normal behavior? Is there any solution for this issue?
Here is my interceptor:
import { Injectable, Injector, Inject, PLATFORM_ID } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';
import { makeStateKey, TransferState } from '@angular/platform-browser';
import { isPlatformServer, isPlatformBrowser } from '@angular/common';
const AUTH_STATE = makeStateKey<string>('authState');
@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
private isServer: boolean;
constructor(private tstate: TransferState, @Inject(PLATFORM_ID) private platformId) {
this.isServer = isPlatformServer(platformId);
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("intercepted request ... ");
let authReq: any = req;
if (this.tstate.hasKey(AUTH_STATE)) {
// We are in the browser
authReq = req.clone(
{
headers: req.headers.set("Auth", this.tstate.get(AUTH_STATE, ''))
}
);
console.log("CLIENT")
console.log(this.tstate.get(AUTH_STATE, ''))
} else if (this.isServer) {
// We are on the server
authReq = req.clone(
{
headers: req.headers.set("Auth", "fromServer")
}
);
console.log("SERVER")
} else {
// State not transfered
let token: any;
token = window.localStorage.getItem("token");
if (token) {
authReq = req.clone(
{
headers: req.headers.set("Auth", token)
})
this.tstate.set(AUTH_STATE, token);
}
console.log("BROWSER")
}
console.log("Sending request with new header now ...");
//send the newly created request
return next.handle(authReq)
.catch((error, caught) => {
//intercept the respons error and displace it to the console
console.log("Error Occurred");
console.log(error);
//return the error to the method that called it
return Observable.throw(error);
}) as any;
}
}
This part: headers: req.headers.set("Auth", "fromServer")
"fromServer" should be replaced with correct token which is in local storage...