javascriptangularcookiessession-cookiesangular-router-guards

AuthGuard Not Recognizing Session Cookie 'sessionId' in Angular App


I'm encountering an issue with my Angular application where the AuthGuard isn't recognizing a session cookie named 'sessionId' correctly. I have implemented user authentication, and the expected behavior is to navigate users to the main page if the 'sessionId' cookie exists, bypassing the signup and signin pages. However, despite verifying that the 'sessionId' cookie is present in my application's cookies, the getCookie function in my CookieService consistently returns null.

Code Snippets:

app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MainPageComponent } from './main-page/main-page.component';
import {AuthGuard} from './shared/auth.guard';
import { ChatComponent } from './shared/chat/chat.component';
import { SidebarLayoutComponent } from './shared/sidebar-layout/sidebar-layout.component';
import { SigninPageComponent } from './signin-page/signin-page.component';
import { SignupPageComponent } from './signup-page/signup-page.component';

const routes: Routes = [
  { path: 'signup', component: SignupPageComponent },
  { path: 'signin', component: SigninPageComponent },
  {
    path: '',
    component: MainPageComponent,
    canActivate: [AuthGuard],
    children: [
      { path: '', component: SidebarLayoutComponent, outlet: 'sidebar' },
      { path: '', component: ChatComponent, outlet: 'chat' }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

auth.guard.ts:

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(
  private auth: AuthService,
  private router: Router
) {}

canActivate(
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
  if (this.auth.isAuthenticated()) {
    return true; // This allows access to the protected route.
  } else {
    console.error('User is not authenticated');
    return this.router.createUrlTree(['/signin']);
  }
}
}

auth.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CookieService } from './cookie.service';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(
    private http: HttpClient,
    private cookieService: CookieService
  ) {}

  authRequest(url: string, User: object ) {
    return this.http.post(url, User, {observe: 'response', withCredentials: true });
  };

  isAuthenticated(): boolean {
    const token = this.cookieService.getCookie('sessionId');
    console.log('Token:', token);
    return !!token;
  }

}

cookies.service.ts:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CookieService {
getCookie(name: string): string | null {
  const allCookies = document.cookie;
  console.log('All Cookies:', allCookies);

  const cookieValue = allCookies
    .split('; ')
    .find(row => row.trim().startsWith(name + '='));

  if (cookieValue) {
    return cookieValue.split('=')[1];
  }

  return null;
}
}

Golang Set-cookie code:

    session := sessions.Default(c)
    session.Options(sessions.Options{
      Path:     "/", // Set the desired path
      Domain:   "localhost", // Set the desired domain
      MaxAge:   4200, // Set other attributes as needed
      HttpOnly: true,
      Secure:   false,
      SameSite: http.SameSiteNoneMode,
})
session.Set("sessionId", id)
err = session.Save()
if err != nil {
    c.AbortWithError(http.StatusInternalServerError, err)
    return
}

c.Status(http.StatusCreated)

Screenshots: signin enter image description here enter image description here

I have already confirmed the presence of the 'sessionId' cookie both in my application's storage and in the browser's developer tools, so I'm confident that the cookie exists. However, the getCookie function still returns null. This issue prevents me from navigating users to the main page when they have an active session. If I need to provide another file, please tell me


Solution

  • There is a piece of devtools that is barely in the viewport. the column name is Http Only and the value is true. That means that this cookie can not be read from the javascript and this behavior is expected.

    If you want to be able to read the corresponding cooke set HttpOnly to false