Currently, I am working on implementing an authentication guard in Angular. Instead of the conventional method of checking local storage or cookies to verify user authentication, I am utilizing API endpoints that respond with 200 OK
if a httponly cookie containing the JWT is attached to the request, and 401 Unauthorized
otherwise.
This is the approach I have taken:
// auth.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class AuthService {
constructor(
private httpClient: HttpClient,
) {}
login(username: string, password: string) {
return this.httpClient.post('/users/login', { username, password });
}
isLoggedIn(): boolean {
this.httpClient.get('/users/check').subscribe({
next: (data) => {
return true;
},
error: () => {
return false;
},
});
return false;
}
}
// auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
if (!this.authService.isLoggedIn()) {
this.router.navigate(['login']);
return false;
}
return true;
}
}
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { LayoutComponent } from './layout/layout.component';
import { ProjectsComponent } from './projects/projects.component';
import { AuthGuard } from './core/auth/auth.guard';
const routes: Routes = [
{
path: '',
component: LayoutComponent,
canActivate: [AuthGuard],
children: [{ path: 'projects', component: ProjectsComponent }],
},
{ path: 'login', component: LoginComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
However, there seems to be a problem once a user logs in and the authentication cookie is set. The isLoggedIn()
function still returns false, redirecting the user back to the login page. My assumption is that I may not be handling the observable from httpclient
correctly, causing it to return false;
before the request finishes?
Any assistance would be greatly appreciated. Thank you in advance!