在 Angular 中读取 CanActivate 路由保护中的 cookie
Read cookie in CanActivate route guard in Angular
我正在使用 Angular 9 和 CanAngular 接口来保护在用户未登录时调用的路由。在登录期间我设置了一个 cookie session_key
,但是我不知道如何在界面的 canActivate
函数中再次 read/get cookie 值。
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private accountService: AccountService
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (cookieExists("session_key")) { <----------------------
// authorised so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/account/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}
我会为 cookieExists
使用什么现有功能?
您可以使用一个简单的实用函数来检查它:
export function cookieExists(cookie: string): boolean {
return document.cookie
.split(';')
.some((item) => item.trim().startsWith(`${cookie}=`)));
}
并在您的 canActivate
:
中使用它
canActivate(): boolean | UrlTree {
if (cookieExists('session_key')) {
return true;
}
return this.router.createUrlTree(
['/account/login'],
{ queryParams: { returnUrl: state.url }}
);
}
从守卫重定向的正确方法是返回 UrlTree
如果您正在使用ngx-cookie-service您需要在authguard中导入Cookie服务。
import { CookieService } from 'ngx-cookie-service';
并在构造函数中注入 cookie 服务
constructor(private cookieService : CookieService){}
然后您可以使用以下代码访问cookie存储
if (cookieService.get("session_key")) {
return true;
}
您可以使用以下代码设置 cookie
cookieService.set('session-key','some-value');
我正在使用 Angular 9 和 CanAngular 接口来保护在用户未登录时调用的路由。在登录期间我设置了一个 cookie session_key
,但是我不知道如何在界面的 canActivate
函数中再次 read/get cookie 值。
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private accountService: AccountService
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (cookieExists("session_key")) { <----------------------
// authorised so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/account/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}
我会为 cookieExists
使用什么现有功能?
您可以使用一个简单的实用函数来检查它:
export function cookieExists(cookie: string): boolean {
return document.cookie
.split(';')
.some((item) => item.trim().startsWith(`${cookie}=`)));
}
并在您的 canActivate
:
canActivate(): boolean | UrlTree {
if (cookieExists('session_key')) {
return true;
}
return this.router.createUrlTree(
['/account/login'],
{ queryParams: { returnUrl: state.url }}
);
}
从守卫重定向的正确方法是返回 UrlTree
如果您正在使用ngx-cookie-service您需要在authguard中导入Cookie服务。
import { CookieService } from 'ngx-cookie-service';
并在构造函数中注入 cookie 服务
constructor(private cookieService : CookieService){}
然后您可以使用以下代码访问cookie存储
if (cookieService.get("session_key")) {
return true;
}
您可以使用以下代码设置 cookie
cookieService.set('session-key','some-value');