要实现Angular身份验证守卫和使用Cookie存储用户信息,可以按照以下步骤进行操作:
ngx-cookie-service
库,该库提供了对Cookie的操作方法。可以使用以下命令进行安装:npm install ngx-cookie-service
auth.guard.ts
的新文件,并编写身份验证守卫的代码。以下是一个基本的示例:import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private cookieService: CookieService, private router: Router) {}
canActivate(): boolean {
const isAuthenticated = this.cookieService.get('isAuthenticated') === 'true';
if (!isAuthenticated) {
this.router.navigate(['/login']);
}
return isAuthenticated;
}
}
AuthGuard
。例如,如果要保护名为dashboard
的路由,可以在路由配置中添加以下代码:import { AuthGuard } from './auth.guard';
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
// 其他路由
];
import { Component } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
@Component({
selector: 'app-login',
template: `
`,
})
export class LoginComponent {
constructor(private cookieService: CookieService) {}
login(): void {
// 执行身份验证逻辑,并将结果存储在Cookie中
const isAuthenticated = true;
this.cookieService.set('isAuthenticated', String(isAuthenticated));
}
}
app.js
文件中添加以下代码:const express = require('express');
const app = express();
// 允许跨域访问
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
// 启用Cookie会话
app.use(session({
secret: 'your-secret-key',
resave: true,
saveUninitialized: true,
}));
// 其他中间件和路由配置
app.listen(process.env.PORT || 3000);
请注意,以上代码仅为示例,并未包含完整的身份验证和路由配置。你需要根据自己的需求进行修改和扩展。