日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
使用Angular和Node進行基于令牌的身份驗證

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

創(chuàng)新互聯(lián)公司專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于成都做網(wǎng)站、成都網(wǎng)站設(shè)計、泉州網(wǎng)絡(luò)推廣、小程序開發(fā)、泉州網(wǎng)絡(luò)營銷、泉州企業(yè)策劃、泉州品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們最大的嘉獎;創(chuàng)新互聯(lián)公司為所有大學(xué)生創(chuàng)業(yè)者提供泉州建站搭建服務(wù),24小時服務(wù)熱線:028-86922220,官方網(wǎng)址:www.cdcxhl.com

第一步:設(shè)置Node.js環(huán)境

確保你已經(jīng)安裝了Node.js和npm(Node包管理器),接下來,創(chuàng)建一個新的Node.js項目并初始化npm。

mkdir tokenauthentication
cd tokenauthentication
npm init y

安裝Express作為我們的服務(wù)器框架和一些其他必要的依賴項:

npm install express jsonwebtoken bcryptjs cors

第二步:創(chuàng)建服務(wù)器和用戶模型

創(chuàng)建一個server.js文件來設(shè)置Express服務(wù)器,并定義一個簡單的用戶模型用于存儲用戶名和哈希過的密碼。

// 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 = []; // 在真實的應(yīng)用中,這將是一個數(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();
    }
});

確保你設(shè)置了一個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服務(wù)和組件

在Angular應(yīng)用中,我們需要創(chuàng)建服務(wù)來處理與后端通信的邏輯,創(chuàng)建一個名為auth.service.ts的服務(wù):

// 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服務(wù)器node server.js,然后在另一個終端窗口啟動Angular開發(fā)服務(wù)器ng serve,打開瀏覽器訪問http://localhost:4200/login,你應(yīng)該可以看到登錄界面,輸入注冊過的用戶信息,然后登錄,成功登錄后,前端會保存令牌,并在后續(xù)請求中使用它。

這個簡單的示例展示了如何使用Angular和Node.js實現(xiàn)基于令牌的身份驗證,在真實場景中,你可能還需要增加更多的安全措施,例如HTTPS、錯誤處理、刷新令牌等,不過,這個基礎(chǔ)版本的實現(xiàn)應(yīng)該提供了一個很好的起點。


文章標(biāo)題:使用Angular和Node進行基于令牌的身份驗證
文章位置:http://m.5511xx.com/article/djchchh.html