您好,登錄后才能下訂單哦!
在AngularJS項目中集成JSON Web Tokens(JWT)進行身份驗證涉及多個步驟。以下是一個基本的指南,幫助你完成這個過程:
首先,你需要一個后端服務來生成和驗證JWT。這里假設你使用的是Node.js和Express。
npm install express jsonwebtoken bcryptjs body-parser
創建一個基本的Express應用,并設置JWT密鑰。
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const SECRET_KEY = 'your-secret-key';
// 模擬用戶數據庫
const users = [
{ id: 1, username: 'user1', password: '$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga36' // 'password1' encrypted
};
// 注冊新用戶
app.post('/register', async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
users.push({ id: Date.now(), username, password: hashedPassword });
res.status(201).send('User registered');
});
// 登錄用戶并返回JWT
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (!user || !await bcrypt.compare(password, user.password)) {
return res.status(401).send('Invalid credentials');
}
const token = jwt.sign({ id: user.id }, SECRET_KEY, { expiresIn: '1h' });
res.json({ token });
});
// 保護路由
app.get('/protected', verifyToken, (req, res) => {
jwt.verify(req.token, SECRET_KEY, (err, decoded) => {
if (err) return res.status(500).send('Failed to authenticate token');
res.json({ message: 'This is a protected route', user: decoded });
});
});
// JWT驗證中間件
function verifyToken(req, res, next) {
const bearerHeader = req.headers['authorization'];
if (typeof bearerHeader !== 'undefined') {
const bearerToken = bearerHeader.split(' ')[1];
req.token = bearerToken;
next();
} else {
res.status(403).send('No token provided');
}
}
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
接下來,我們設置AngularJS應用,并使用$http
服務與后端交互。
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS JWT Authentication</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-controller="mainController">
<h1>AngularJS JWT Authentication</h1>
<button ng-click="register()">Register</button>
<button ng-click="login()">Login</button>
<button ng-click="protected()">Protected Route</button>
<div ng-if="message">{{message}}</div>
<script>
const app = angular.module('myApp', []);
app.controller('mainController', ['$scope', '$http', function($scope, $http) {
$scope.message = '';
$scope.register = async () => {
const response = await $http.post('http://localhost:3000/register', { username: 'user1', password: 'password1' });
$scope.message = response.data;
};
$scope.login = async () => {
const response = await $http.post('http://localhost:3000/login', { username: 'user1', password: 'password1' });
localStorage.setItem('token', response.data.token);
$scope.message = response.data;
};
$scope.protected = async () => {
const token = localStorage.getItem('token');
if (token) {
const response = await $http.get('http://localhost:3000/protected', { headers: { Authorization: `Bearer ${token}` } });
$scope.message = response.data.message;
} else {
$scope.message = 'No token provided';
}
};
}]);
</script>
</body>
</html>
確保你的后端服務和AngularJS應用都在運行狀態。
啟動后端服務:
node server.js
打開AngularJS應用:
打開瀏覽器,訪問http://localhost:3000
。
通過以上步驟,你已經在AngularJS項目中成功集成了JWT進行身份驗證。用戶可以注冊新賬戶,登錄并訪問受保護的資源。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。