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.
我的角度应用程序遇到一个问题,AuthGuard无法正确识别名为‘essionID’的会话Cookie。我已经实现了用户身份验证,预期的行为是,如果‘essionID’cookie存在,则将用户导航到主页,绕过注册和登录页面。然而,尽管验证了我的应用程序的Cookie中存在‘essionID’Cookie,但我的CookieService中的getCookie函数始终返回空。
- Angular version: 15.2.0
- Backend Golang version: 1.20
Code Snippets:
代码片段:
app-routing.module.ts
:
App-routing.mode.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
:
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
:
Auth.Serice.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
:
Cookies.Serice.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
:
Golang Set-Cookie代码:
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
:
截图:
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
我已经确认了在我的应用程序存储和浏览器的开发工具中都存在‘会话ID’Cookie,所以我确信该Cookie存在。但是,getCookie函数仍然返回NULL。当用户有活动会话时,此问题会阻止我将用户导航到主页。如果我需要提供其他文件,请告诉我
更多回答
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.
有一块DevTool几乎不在视口中。列名仅为http,值为TRUE。这意味着不能从Java脚本中读取该cookie,这是预期的行为。
If you want to be able to read the corresponding cooke set HttpOnly to false
如果您希望能够读取相应的Cooke,请将HttpOnly设置为False
更多回答
It works, thank you very much!
它起作用了,非常感谢!
我是一名优秀的程序员,十分优秀!