您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。