我的 Angular 应用程序遇到问题,AuthGuard 无法正确识别名为“sessionId”的会话 cookie。我已经实现了用户身份验证,预期行为是如果“sessionId”cookie 存在,则将用户导航到主页,绕过注册和登录页面。然而,尽管验证了“sessionId”cookie 是否存在于我的应用程序的 cookie 中,我的 CookieService 中的 getCookie 函数始终返回 null。
代码片段:
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
:
我已经确认我的应用程序存储和浏览器的开发人员工具中都存在“sessionId”cookie,因此我确信该 cookie 存在。但是,getCookie 函数仍然返回 null。此问题使我无法在用户进行活动会话时将其导航到主页。如果我需要提供其他文件,请告诉我
有一个开发工具几乎不在视口中。列名称为 Http Only,值为
true
。这意味着无法从 javascript 读取此 cookie,并且此行为是预期的