【问题标题】:AdonisJS Socket.IO JWT authenticationAdonisJS Socket.IO JWT 认证
【发布时间】:2020-11-29 06:07:09
【问题描述】:

如何定义身份验证提供程序?现在每次在 playerLogin 方法中未定义 auth 变量。

我正在使用 Adonis v4.1

代码: 启动/socket.js

const Server = use('Server')
const io = use('socket.io')(Server.getInstance())

// Define controllers here
// Example: const WSController = use('App/Controllers/Http/ChatController')
const AuthenticateController = use('App/Controllers/Http/AuthenticateController');

io.on('connection', function (socket) {
  // Define here the controller methods
  // Example: WSController.goMessage(socket, io)
  AuthenticateController.playerLogin(socket, io);
  AuthenticateController.playerRegister(socket, io);
})

AuthenticateController.js

const Hash = use('Hash')
const User = use('App/Models/User')

class AuthenticateController {
    static playerLogin(socket, io, {auth}) {
        socket.on('playerLogin', async (data) => {
            console.log('WORKS')
            if (await auth.attempt(data.email, data.password)) {
                let user = await User.findBy('email', data.email)
                let accessToken = await auth.generate(user)
                socket.emit('sendPlayerToken', { token: accessToken });
            } else {
                socket.emit('sendPlayerToken', { token: 'Credentials are incorrect' });
            }
        });
    }

    static playerRegister(socket, io) {
        socket.on('playerRegister', async (data) => {
            const safePassword = await Hash.make(data.password)
            const user = new User()
            user.username = data.username
            user.email = data.email
            user.password = safePassword
            await user.save()
            socket.emit('sendPlayerRegister', { success: true });
        });
    }
}

亲切的问候,

玉米

【问题讨论】:

    标签: socket.io jwt adonis.js


    【解决方案1】:

    正如下面的讨论:

    https://github.com/adonisjs/core/discussions/2051?sort=new#discussioncomment-274111

    您可以使用 API 防护并使用 M4gie 答案中的代码进行身份验证。

    您只需要安装带有yarn add crypto的crypto包,如果您不想创建显示套接字错误的对象,只需将其转换为字符串:throw new Error('SocketErrors:MissingParameter')

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 2020-08-20
      • 2021-12-25
      • 2011-06-12
      • 2021-02-24
      • 2019-05-23
      • 2021-03-05
      • 2016-01-12
      相关资源
      最近更新 更多