how to retained user session logged in between tabs?

1000 Views Asked by At

In an Angular application I am trying to retain user's logged_in property until he manually logs out using localStorage. Though the data is encrypted and saved in localStorage, we can manually copy the data and paste it in after a user logs out, then security is broken here (we will be able to access the application without logging in just with the encrypted key). How can we achieve this functionality? It is okay if a user gets logged out if he closes all tabs. Instead of using localStorage/SessionStorage/Cookie, how can we achieve this? What is the best way to implement this?

2

There are 2 best solutions below

3
Morsh On

One way to approach this would be to have JWT stored in localstorage. Thereby, upon starting the application(By visiting the url) trigger a service method to send the JWT token to the backend and validate it. If the validation is successful, proceed with normal flow else clear the localstorage and navigate to login page.

The best place to do this would be at the ngOnInit of the app.component. Moreover the JWT can have expiration time, hence after a stipulated time (Preferably an hour which can be configured), the token becomes invalid. This can be done to avoid any other user to use the same credential. In app.component.ts

   ...
    export class AppComponent implements onInit{
        constructor(private authService: AuthService){
        }   
        ngOnInit(){
            this.authService.authenticate()
        }
    }

In AuthService

...
export class AuthService{
    token: string;  

    constructor(private http: HttpClient,private router: Router){
    }

    authenticate(){
        this.token = localStorage.get("JWT");
        this.http.post<any>("YOUR_BACKEND",{token: this.token})
        .subscribe((data)=>{
            //do nothing        
        },
        (err)=>{
            this.router.navigate(["/login"]);   
            localstorage.removeItem("JWT")
        })          
    }   

    ...
}
0
user2900572 On

Since using cookie seems to be moderate vulnerability, i used cookies with encoded data.