[英]Read cookie in CanActivate route guard in Angular
我正在使用 Angular 9 和CanAngular接口来保护在用户未登录时调用的路由。在登录期间,我设置了一个 cookie session_key
,但我不知道如何在canActivate
中再次读取/获取 cookie 值function 的接口。
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 使用哪些现有的cookieExists
?
您可以使用一个简单的实用程序 function 来检查它:
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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.