av激情亚洲男人的天堂国语,日韩欧美精品一中文字幕,无码av一区二区三区无码,国产又色又爽又刺激的a片,国产又色又爽又刺激的a片

使用Angular和Node進(jìn)行基于令牌的身份驗(yàn)證

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

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

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

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

mkdir tokenauthentication
cd tokenauthentication
npm init y

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

npm install express jsonwebtoken bcryptjs cors

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

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

// 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í)的應(yīng)用中,這將是一個(gè)數(shù)據(jù)庫(kù)
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'));

第三步:實(shí)現(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è)置了一個(gè)ACCESS_TOKEN_SECRET環(huán)境變量,它將被用來(lái)簽名令牌。

第四步:創(chuàng)建Angular前端

生成新的Angular項(xiàng)目,并安裝必要的依賴項(xiàng):

ng new angularclient
cd angularclient
npm install @angular/common @angular/core @angular/forms @angular/http @angular/material @angular/platformbrowser @angular/platformbrowserdynamic @angular/router rxjs

第五步:實(shí)現(xiàn)Angular服務(wù)和組件

在Angular應(yīng)用中,我們需要?jiǎng)?chuàng)建服務(wù)來(lái)處理與后端通信的邏輯,創(chuàng)建一個(gè)名為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)建一個(gè)登錄表單組件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包含了一個(gè)表單,該表單可以輸入用戶名和密碼,并且有一個(gè)按鈕調(diào)用login()方法。

第六步:集成和測(cè)試

現(xiàn)在你可以運(yùn)行Node.js服務(wù)器node server.js,然后在另一個(gè)終端窗口啟動(dòng)Angular開發(fā)服務(wù)器ng serve,打開瀏覽器訪問(wèn)http://localhost:4200/login,你應(yīng)該可以看到登錄界面,輸入注冊(cè)過(guò)的用戶信息,然后登錄,成功登錄后,前端會(huì)保存令牌,并在后續(xù)請(qǐng)求中使用它。

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


新聞名稱:使用Angular和Node進(jìn)行基于令牌的身份驗(yàn)證
URL鏈接:http://uogjgqi.cn/article/djchchh.html
掃二維碼與項(xiàng)目經(jīng)理溝通

我們?cè)谖⑿派?4小時(shí)期待你的聲音

解答本文疑問(wèn)/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流