新聞中心
基于令牌的身份驗證是一種廣泛采用的安全機制,允許應用程序在用戶登錄后進行身份驗證和授權,在這個過程中,服務器會生成一個令牌,然后將其返回給客戶端,客戶端隨后的每個請求都需要攜帶這個令牌,以證明其身份,在這個回答中,我們將使用Angular作為前端框架,Node.js作為后端服務器,以及JSON Web Tokens (JWT) 實現(xiàn)基于令牌的身份驗證。

創(chuàng)新互聯(lián)公司專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務,包含不限于成都做網(wǎng)站、成都網(wǎng)站設計、泉州網(wǎng)絡推廣、小程序開發(fā)、泉州網(wǎng)絡營銷、泉州企業(yè)策劃、泉州品牌公關、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務,您的肯定,是我們最大的嘉獎;創(chuàng)新互聯(lián)公司為所有大學生創(chuàng)業(yè)者提供泉州建站搭建服務,24小時服務熱線:028-86922220,官方網(wǎng)址:www.cdcxhl.com
第一步:設置Node.js環(huán)境
確保你已經(jīng)安裝了Node.js和npm(Node包管理器),接下來,創(chuàng)建一個新的Node.js項目并初始化npm。
mkdir tokenauthentication cd tokenauthentication npm init y
安裝Express作為我們的服務器框架和一些其他必要的依賴項:
npm install express jsonwebtoken bcryptjs cors
第二步:創(chuàng)建服務器和用戶模型
創(chuàng)建一個server.js文件來設置Express服務器,并定義一個簡單的用戶模型用于存儲用戶名和哈希過的密碼。
// server.js
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const cors = require('cors');
const app = express();
app.use(cors());
let users = []; // 在真實的應用中,這將是一個數(shù)據(jù)庫
app.post('/register', (req, res) => {
const hashedPassword = bcrypt.hashSync(req.body.password, 8);
users.push({
id: Date.now().toString(),
name: req.body.name,
password: hashedPassword,
});
res.status(201).send();
});
app.listen(3000, () => console.log('Server running on port 3000'));
第三步:實現(xiàn)登錄和令牌生成
繼續(xù)在server.js中添加登錄路由和令牌生成邏輯。
//...之前的代碼...
app.post('/login', (req, res) => {
const user = users.find((u) => u.name === req.body.name);
if (user == null) {
return res.status(400).send('Cannot find user');
}
try {
if (bcrypt.compareSync(req.body.password, user.password)) {
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET);
res.json({ accessToken: accessToken });
} else {
res.send('Not Allowed');
}
} catch {
res.status(500).send();
}
});
確保你設置了一個ACCESS_TOKEN_SECRET環(huán)境變量,它將被用來簽名令牌。
第四步:創(chuàng)建Angular前端
生成新的Angular項目,并安裝必要的依賴項:
ng new angularclient cd angularclient npm install @angular/common @angular/core @angular/forms @angular/http @angular/material @angular/platformbrowser @angular/platformbrowserdynamic @angular/router rxjs
第五步:實現(xiàn)Angular服務和組件
在Angular應用中,我們需要創(chuàng)建服務來處理與后端通信的邏輯,創(chuàng)建一個名為auth.service.ts的服務:
// src/app/auth.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class AuthService {
login(userName: string, password: string) {
return this.http.post(http://localhost:3000/login, { name: userName, password })
.pipe(map(user => {
if (user && user.accessToken) {
localStorage.setItem('currentUser', JSON.stringify(user));
}
return user;
}));
}
logout() {
localStorage.removeItem('currentUser');
}
}
創(chuàng)建一個登錄表單組件login.component.ts:
// src/app/login/login.component.ts
import { Component } from '@angular/core';
import { AuthService } from '../auth.service';
@Component({
selector: 'applogin',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
userName: string;
password: string;
constructor(private authService: AuthService) {}
login() {
this.authService.login(this.userName, this.password);
}
}
確保你的login.component.html包含了一個表單,該表單可以輸入用戶名和密碼,并且有一個按鈕調(diào)用login()方法。
第六步:集成和測試
現(xiàn)在你可以運行Node.js服務器node server.js,然后在另一個終端窗口啟動Angular開發(fā)服務器ng serve,打開瀏覽器訪問http://localhost:4200/login,你應該可以看到登錄界面,輸入注冊過的用戶信息,然后登錄,成功登錄后,前端會保存令牌,并在后續(xù)請求中使用它。
這個簡單的示例展示了如何使用Angular和Node.js實現(xiàn)基于令牌的身份驗證,在真實場景中,你可能還需要增加更多的安全措施,例如HTTPS、錯誤處理、刷新令牌等,不過,這個基礎版本的實現(xiàn)應該提供了一個很好的起點。
文章名稱:使用Angular和Node進行基于令牌的身份驗證
URL地址:http://fisionsoft.com.cn/article/djchchh.html


咨詢
建站咨詢
