Reputation: 360
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
Upvotes: 0
Views: 1219
Reputation: 360
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
Upvotes: 2