Jwt是一种用于在应用程序之间传递身份验证信息的开放标准。将Jwt保护的Express.js Rest api与Angular应用程序连接可以通过以下步骤完成:
jsonwebtoken
模块,它将用于生成和验证Jwt令牌。下面是一个示例代码,演示如何将Jwt保护的Express.js Rest api与Angular应用程序连接:
在Express.js Rest api中的auth.js
文件中:
const jwt = require('jsonwebtoken');
const express = require('express');
const router = express.Router();
const secretKey = 'your_secret_key'; // 设置密钥
// 创建用于生成Jwt令牌的路由处理程序
router.post('/login', (req, res) => {
// 假设验证用户名和密码成功
const username = req.body.username;
const token = jwt.sign({ username: username }, secretKey, { expiresIn: '1h' });
res.json({ token: token });
});
// 在受保护的路由中验证Jwt令牌
router.get('/protected', (req, res) => {
const token = req.headers.authorization.split(' ')[1];
jwt.verify(token, secretKey, (err, decoded) => {
if (err) {
return res.status(401).json({ message: '无效的令牌' });
}
return res.json({ message: '成功访问受保护的路由' });
});
});
module.exports = router;
在Angular应用程序中的auth.service.ts
文件中:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private apiUrl = 'http://your-api-url/auth'; // 替换为你的Express.js Rest api的URL
constructor(private http: HttpClient) { }
login(username: string, password: string): Observable<any> {
const body = { username: username, password: password };
return this.http.post(`${this.apiUrl}/login`, body);
}
protectedRoute(): Observable<any> {
const token = localStorage.getItem('token');
const headers = new HttpHeaders({ 'Authorization': `Bearer ${token}` });
return this.http.get(`${this.apiUrl}/protected`, { headers: headers });
}
}
在Angular应用程序中的login.component.ts
文件中:
import { Component } from '@angular/core';
import { AuthService } from './auth.service';
@Component({
selector: 'app-login',
template: `
<h1>Login</h1>
<form (ngSubmit)="onSubmit()">
<input type="text" [(ngModel)]="username" name="username" placeholder="用户名" required>
<input type="password" [(ngModel)]="password" name="password" placeholder="密码" required>
<button type="submit">登录</button>
</form>
`,
})
export class LoginComponent {
username: string;
password: string;
constructor(private authService: AuthService) { }
onSubmit() {
this.authService.login(this.username, this.password).subscribe((response) => {
localStorage.setItem('token', response.token);
// 导航到受保护的页面
});
}
}
在Angular应用程序中的protected.component.ts
文件中:
import { Component } from '@angular/core';
import { AuthService } from './auth.service';
@Component({
selector: 'app-protected',
template: `
<h1>Protected Route</h1>
<p>{{ message }}</p>
`,
})
export class ProtectedComponent {
message: string;
constructor(private authService: AuthService) {
this.authService.protectedRoute().subscribe((response) => {
this.message = response.message;
});
}
}
这是一个简单的示例,展示了如何将Jwt保护的Express.js Rest api与Angular应用程序连接。请根据实际情况进行修改和扩展。有关更多详细信息和腾讯云产品的推荐,请参考腾讯云官方文档和产品介绍。
领取专属 10元无门槛券
手把手带您无忧上云