What is the best way to login auth?

Asked

Viewed 73 times

3

Authservice

login(user: User){
    return this.http.post<any>(`${this.API_URL}`, {
        email: user.username,
        password: user.password
    });
}

isUserLoggedIn(){
    return this.http.get<any>(`${this.API_URL}/1`);
}

logoff(){
    //this.loggedIn.next(null);
    this.router.navigate(['/login']);
}

Logincomponent

onSubmit(){
    this.submitted = true;
    this.authService.login(this.loginForm.value).subscribe(r => {
        if(r.success){
            this.router.navigate(['/home']);
        }
    });
}

Auth Guard

canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
): any{
    return this.authService.isUserLoggedIn()
    .pipe(
        map(res => {
            if (res.isAuth){
                return true;
            }
            this.router.navigate(['/login']); 
            return false;
        })
    );
}
  • I have a Service (AuthService);
  • In the LoginComponent: Send the data to a API to log in (send username and password) returning sucesso if the user exists;
  • In the Guard: Other service (isUserLoggedIn()) checks if the user is logged in and if the sessão is still alive.

Is there another approach to user authentication in Angular 4+? Would this approach be used in most projects?

1 answer

1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.