[v4] Authenticate Adonis Websocket Connections #1726
Answered
by
kempsteven
kempsteven
asked this question in
Help
-
So problem is I can't add Authorization header in the client-side to use the middleware 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 JWT 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 |
Beta Was this translation helpful? Give feedback.
Answered by
kempsteven
Oct 9, 2020
Replies: 1 comment
-
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 |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
kempsteven
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So i just used jsonwebtoken plugin to verify if the jwt token is valid.
Here is the middleware: