简体   繁体   中英

Authenticate Adonis Websocket Connections

Adonis.js Version 4.x

So problem is I can't add Authorization header in the client-side to use the middleware Adonis/Middleware/Auth to authenticate my JWT Token.

So what I did is I made a customer middleware for authorizing the socket connection, I can now get the token I passed. So now how do I check if that token is valid? I haven't seen any good documentation on this part, advanced thanks for the help!

Client Side

import Ws from '@adonisjs/websocket-client'

const ws = Ws('ws://0.0.0.0:3001', {
      path: 'adonis-ws'
})

const jwtToken = cookie.get('auth._token.local')

ws
   .withJwtToken(jwtToken)
   .connect()

Server Side

// start/socket.js
const Ws = use('Ws')
Ws.channel('order', 'OrderController').middleware(['socketAuth'])
// start/wsKernel.js
const Ws = use('Ws')

const namedMiddleware = {
  socketAuth: 'App/Middleware/SocketAuthentication'
}

Ws
  .registerGlobal(globalMiddleware)
  .registerNamed(namedMiddleware)
// app/Middleware/SocketAuthentication.js
class SocketAuthentication {
  async wsHandle ({ request, auth }, next) {
    try {
      const { token } = request.all()
      // Authenticate the error in this part :(
      await next()
    } catch (error) {
      console.log(error)
    }
  }
}

module.exports = SocketAuthentication

So i just used jsonwebtoken plugin to verify if the jwt token is valid.

Here is the middleware:

'use strict'
const Env = use('Env')
const jwt = require('jsonwebtoken')

class SocketAuthentication {
  /**
  * @param {object} ctx
  * @param {Request} ctx.request
  * @param {Function} next
  */
  async wsHandle ({ request, auth }, next) {
    const { token } = request.all()
    const appKey = auth.authenticatorInstance._config.options.secret
    const jwtToken = token.split(' ')[1]
    jwt.verify(jwtToken, appKey)
    await next()
  }
}

module.exports = SocketAuthentication

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM