服务器端:
var express = require('express');
var http = require('http');
var path = require('path');
var socketIO = require('socket.io');
var socketioJwt = require('socketio-jwt');
var app = express();
var server = http.Server(app);
var io = socketIO(server);
app.use('/files', express.static(__dirname + '/files'));
app.get('/', function(request, response) {
response.sendFile('G:/jwtclient.html');
});
// Accept connection and authorize token
io.on('connection', socketioJwt.authorize({
secret: 'SECRET_KEY',
timeout: 15000,
}));
io.on('authenticated', function (socket) {
console.log(socket.decoded_token);
console.log('Authenticated!');
});
server.listen(1111);
客户端:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Js1</title>
<link href="" rel="stylesheet" type="text/css">
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<p id = 'test'></p>
<script>var token = sessionStorage.token;
var socket = io('localhost:1111');
socket.on('connect', function () {
console.log('connected!');
socket.on('authenticated', function () {
document.getElementById('test').innerHTML = 'Authenticated!!!';
});
socket.emit('authenticate', {token: token}); //send the jwt
});
</script>
</body>
</html>
我确实获得了“联系!”登录我的控制台,但是似乎没有进行身份验证。我不知道我在做什么错。任何帮助将不胜感激。
编辑:我也尝试过:
服务器:
var express = require('express');
var http = require('http');
var path = require('path');
var socketIO = require('socket.io');
var socketioJwt = require('socketio-jwt');
var app = express();
var server = http.Server(app);
var io = socketIO(server);
app.use('/files', express.static(__dirname + '/files'));
app.get('/', function(request, response) {
response.sendFile('G:/jwtclient.html');
});
io.use(socketioJwt.authorize({
secret: 'secret',
handshake: true,
}));
// Accept connection and authorize token
io.on('connection', function() {
console.log('authorized');
});
server.listen(1111);
客户:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Js1</title>
<link href="" rel="stylesheet" type="text/css">
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<p id = 'test'></p>
<script>var token = sessionStorage.token;
var socket = io.connect('http://localhost:1111', {
'query': 'token=' + token,
});
socket.on('connect', function (sock) {
console.log('connected!');
});
</script>
</body>
</html>
两者都与此处的官方文档完全相同:https://www.npmjs.com/package/socketio-jwt
没有任何效果。是只是简单地弃用了该包装并使其变得无用,还是我做错了什么?因为我正在复制文档中的所有内容...
答案 0 :(得分:-1)
在服务器端,您应该像这样接受并验证JWT:
socket.on("authenticate", function(jwt){
socket.emit("authenticated"); // if autehnticated
})