Why is my page is not getting currently logged in when reload?

181 Views Asked by At

I'm using Angular for my website. Initially once the page is launched, there are no issues and it authenticates perfectly. However, when refreshing the page it can't pull the currently login user anymore. It looks like it doesn't call windows authentication. I'm adding my code. Any help is appreciated.

intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {

    console.log('AppInterceptorService1111');
    req = req.clone({
        withCredentials: true
      });

    return next.handle(req)
        .pipe(catchError(this.handleError));
}

The local storage has already been implemented.

this.authenticateCurrentNTLogin().subscribe((data: any) => {
            this.currentUserInfoService.tokenInfo = data.Response;            
            localStorage.setItem('userToken', this.currentUserInfoService.tokenInfo.access_token);
            localStorage.setItem('userRoles', this.currentUserInfoService.tokenInfo.role);        
            this.currentUserInfoService.currentUserTokenExpiration = new Date();
            this.currentUserInfoService.currentUserTokenExpiration.setSeconds(new Date().getSeconds() + parseInt(this.currentUserInfoService.tokenInfo.expires_in));
            localStorage.setItem('myTokenExpiration', this.currentUserInfoService.currentUserTokenExpiration.toLocaleDateString() +
            ' ' + this.currentUserInfoService.currentUserTokenExpiration.toLocaleTimeString());                     
        }, 
2

There are 2 best solutions below

3
Rick On

in my apps, once a user authenticates, I store the username & user_id in localStorage, so it has instant access anywhere in the app.

10
Eranki On

After logging with authentication, store the user id or login id in a variable. And throughout the application you can retrieve this local variable to confirm if user id logged in or not even after refreshing. When he logs out, clear that variable. In other terms, you can use local storage as session on client side. Use the below one when user logs in and when authenticated true.

localStorage.setItem("user", user id)

var user = local storage.getItem("user")

In the page that you are reloading, use .get method and if user is not null then allow him to access current page. If user variable is null, then user is not logged in and redirect him to login page. When user logs out:

local storage.removeItem("user")

Hope this was what you were asking about.